Home System Tutorial MAC How to use Golang with MySQL

How to use Golang with MySQL

Apr 11, 2025 am 10:37 AM

This tutorial guides you through connecting your Golang projects to MySQL databases using the go-sql-driver/mysql driver. We'll cover driver installation, database connection, and basic database operations with practical examples.

Prerequisites: Ensure MySQL is installed and running. Verify this by executing mysql --version in your terminal. The output should display your MySQL version.

How to use Golang with MySQL

Installing the Go MySQL Driver:

Install the necessary driver using:

go get -u github.com/go-sql-driver/mysql

While other drivers exist, this is a popular and well-maintained choice. Refer to its GitHub page for detailed information.

Project Setup:

Create your Golang project directory. If not working within your Go installation directory, use these commands to initialize a Go module:

go mod init test-sql go mod tidy

This generates go.mod and go.sum files, essential for managing dependencies.

Connecting to MySQL:

Create a main.go file and add the following code:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/test")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    fmt.Println("Successfully connected to MySQL!")
}</your_mysql_password>
Copy after login

Remember to replace <your_mysql_password></your_mysql_password> with your actual MySQL database password. We recommend using a password manager for secure storage.

Use a code editor (like CodeRunner) to write and run this code. After saving, navigate to the project directory in your terminal and run:

go run main.go

A "Successfully connected to MySQL!" message confirms a successful connection.

How to use Golang with MySQL

Creating a MySQL Database:

For this tutorial, we'll use a database management tool like TablePlus to create a database (e.g., "123begin") and a table (e.g., "testtable2"). Adapt the following examples to your specific database and table names.

How to use Golang with MySQL

Database Operations:

Inserting Data:

This code inserts data into your table:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    insert, err := db.Query("INSERT INTO testtable2 VALUES('23')")
    if err != nil {
        panic(err.Error())
    }
    defer insert.Close()
    fmt.Println("Data inserted successfully!")
}</your_mysql_password>
Copy after login

Run go run main.go to execute the insertion.

How to use Golang with MySQL

Querying Data:

This code retrieves data from your table:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

type Testtable2 struct {
    id int `json:"id"`
}

func main() {
    db, err := sql.Open("mysql", "root:<your_mysql_password>@tcp(127.0.0.1:3306)/123begin")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    results, err := db.Query("SELECT id FROM testtable2")
    if err != nil {
        panic(err.Error())
    }
    defer results.Close()
    for results.Next() {
        var testtable2 Testtable2
        err = results.Scan(&testtable2.id)
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}</your_mysql_password>
Copy after login

Run go run main.go to execute the query. The output should show the inserted data.

How to use Golang with MySQL

Troubleshooting:

  • Incorrect Directory: Ensure you're running go run main.go from the correct project directory. Use cd to navigate.
  • Missing go.mod/go.sum: If these files are missing, re-run the go mod init and go mod tidy commands.
  • MySQL Errors: Consult MySQL's official documentation for error resolution.

This enhanced tutorial provides a clearer, more concise, and step-by-step guide to connecting Golang to MySQL. Remember to replace placeholder values with your actual credentials and database information. Using tools like CodeRunner, TablePlus, SnippetsLab, and Secrets can streamline your workflow.

The above is the detailed content of How to use Golang with MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Floating screen recording: how to capture a specific app window on a Mac Floating screen recording: how to capture a specific app window on a Mac Mar 28, 2025 am 09:16 AM

Mac Screen Recording: Easily capture windows, areas and drop-down menus The screenshot tool (Command Shift 5) that comes with Mac systems can record full screen or selected areas, but cannot record specific application windows separately. At this time, more powerful tools are needed to complete the task. This article will introduce several ways to help you record your Mac windows as easily as a professional. Record the application window separately Record a single window to avoid cluttered desktop backgrounds and create more professional and prominent images and videos. Here are some excellent screen recording applications: Function comparison Gifox CleanShot X Dropshare Record a specific window ✓ ✓ ✓

The full list of all macOS versions until 2025 The full list of all macOS versions until 2025 Mar 23, 2025 am 10:08 AM

‎macOS version history macOS 15 Sequoia, September 16, 2024macOS 14 Sonoma,September 26, 2023 macOS 13 Ventura,October 25, 2022

Change the unchangeable PDFs with Nitro PDF Pro Change the unchangeable PDFs with Nitro PDF Pro Mar 22, 2025 am 11:14 AM

You can’t avoid working with PDFs. But what you can avoid is having problems with them. Intractable as they seem, PDFs are actually pretty easy to deal with – not without help, of course. When it comes to making changes in your docs,Nitro PDF Pr

Top 9 AI writing assistants for Mac, iOS, and the web Top 9 AI writing assistants for Mac, iOS, and the web Mar 23, 2025 am 10:44 AM

The market for AI-powered writing assistants is expected to grow rapidly, reaching approximately $6.5 billion by 2030. Since AI writing assistants are here to stay, it's important to learn about the best tools in the industry. In this article, w

How to refresh on a Mac - Setapp How to refresh on a Mac - Setapp Mar 18, 2025 am 11:47 AM

This guide shows you how to refresh various aspects of your Mac, from web pages to the desktop and Messages. Let's dive in! Refreshing Web Pages on Your Mac For a quick refresh, the easiest method is using the keyboard shortcut Command R. This wor

How to convert a PDF to grayscale How to convert a PDF to grayscale Mar 22, 2025 am 10:20 AM

Converting color PDFs to grayscale or black and white can effectively reduce file size, save printing costs, or facilitate previewing. This article will introduce the use of two methods of using Mac's own tools and third-party applications to achieve PDF color conversion. Grayscale images contain a variety of shades of gray from white to black, while true black and white images have only two colors: pure black and pure white. Therefore, for printed documents containing content other than simple text, grayscale is usually the preferred color format. Save PDFs to black and white instead of grayscale, the file size will decrease significantly, but the appearance of all objects except text will change. Therefore, converting PDFs from color to grayscale is usually a safer choice. Method 1: Use Nitro PDF Pro Nitro PD

See all articles