You ask and Eney gets it done. Meet a Computerbeing. Learn More

How to use Go with MySQL

61.2K views
13 min read

TL;DR:

  • Install the Go MySQL driver: go get -u github.com/go-sql-driver/mysql.
  • Connect to your database using sql.Open and test with db.Ping.
  • Use db.Query, db.Exec, and db.Scan for insert, read, update, and delete operations.
  • Make sure your MySQL server is running and your connection string is correct.
  • Use CodeRunner to write and test your Go code, SnippetsLab to organize snippets, Secrets 4 to store passwords safely, and TablePlus to manage databases with ease.

Looking for the best database to use for your Golang projects? MySQL is one of the most popular tools for working with SQL databases. Is it the best one for you? The only way to know is to try it out.

In this article, I’ll walk you through how to connect to MySQL databases using Go, set up your environment for smooth integration, and run basic database operations with hands-on Go + MySQL examples.


Getting started with Go MySQL driver

Here are the first steps you need to take:

  1. Make sure you have MySQL on your machine by running mysql --version command in Terminal.
  2. If you have MySQL, you'll see the MySQL version printed in your Terminal window.
  3. Next, run the installation command for the Golang MySQL driver: go get -u github.com/go-sql-driver/mysql.

run mySQL

You don’t have to use this specific Go MySQL driver, but it’s a popular one, so we are using it for our tutorial. You can find detailed information about this driver on its page on GitHub.

Now, let’s connect to MySQL.

Now, let’s connect to MySQL

Create your application in the folder where you have all your Golang installation files, or run: 

  • go mod init test-sql
  • go mod tidy

This allows you to run your Go app in a folder other than the one you’ve installed Go in.

With that out of the way, you're ready to connect. Create a main.go file and insert the following code:

package main
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    // Replace 'yourpassword' with your actual MySQL root password
    dsn := "root:yourpassword@tcp(127.0.0.1:3306)/test"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
    // Verify the connection is valid
    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }
    fmt.Println("Success!")
}

Make sure that the test database exists in your MySQL server. If it doesn't, you can create it using the MySQL command-line interface: CREATE DATABASE test;.

You can write this code using any code editor you like. I use CodeRunner, a quick code editor with handy syntax highlighters, IDE features, and support for over 25 languages, including Golang. Just copy the above code and insert your MySQL database password in this line:

"root:@tcp(127.0.0.1:3306)/test").

code editor

Once you do this, you're ready to run your Go application in Terminal. First, move to the folder containing your main.go program using the change directory command cd:

run your Go application in Terminal

Next, type go run main.go. Your program will print “Success!” on the screen if everything runs smoothly.

Connecting your Go application to MySQL

To connect your Go application to MySQL:

  1. Create a new Go project folder if you don’t have one already.
  2. Add the go-sql-driver/mysql package to your Go project using go get -u github.com/go-sql-driver/mysql. If you’re using a different database system, adjust the driver name (the “mysql” part) accordingly. 
  3. Write a Go program to connect to MySQL using this code:
import (
    "database/sql"
    "fmt"
    "log"
    "github.com/go-sql-driver/mysql"
)
func main() {
    cfg := mysql.Config{
        User:                 "user",
        Passwd:               "password",
        Net:                  "tcp",
        Addr:                 "localhost:3306",
        DBName:               "database",
        AllowNativePasswords: true,
    }
    db, err := sql.Open("mysql", cfg.FormatDSN())
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    if err = db.Ping(); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Successfully connected to MySQL!")
}

4. Replace user:password@tcp(host:port)/database with your MySQL connection details.

5. Save the code to an executable file and run it using the command go run main.go.

To successfully connect your Go application to MySQL, make sure your MySQL client is properly installed and configured. Manage dependencies in your Go project using Go modules, institute thorough error handling, and use secure methods to store and transmit MySQL secrets.

Setting up your MySQL database for Golang

Before you set up your MySQL database for Golang, you first need to install MySQL using these steps:

  1. Download the installation package from the official MySQL website.
  2. Open the package and follow the installation wizard instructions. 
  3. Set a password for the root user if asked.
  4. Close the wizard once the installation is done. 

You can also install MySQL using Homebrew if it's on your Mac. Simply open Terminal and type the command brew install mysql. To verify your MySQL installation, type the Terminal command mysql --version and run the command mysql -u root -p to start using the server. 


My SQL

Working with a MySQL database

Now that we have our table, let's try to insert some data: a database object.

Here's the code for inserting an object into a table in your database:

package main
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    db, err := sql.Open("mysql", "root:<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("Yay, values added!")
}

Add this code to your main.go file. You can copy your previous code to SnippetsLab to access it for other projects.

Now, run go run main.go command in Terminal in the folder with your Go project. If everything goes right, you should have Yay, values added! printed back:

run main.go command in Terminal

With the new value added, we can have a Golang app do an SQL DB query to check that the value has indeed been added to the table.

Here’s the code I used for this:

package main
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
type Testtable2 struct {
    id int `json:"id"`
}
func main() {
    db, err := sql.Open("mysql", "root:<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())
    }
    for results.Next() {
        var testtable2 Testtable2
        err = results.Scan(&testtable2.id)
        if err !=nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}

Replace testtable2, 123begin, and id with respective values for your database table, database name, and the column you're querying.

Run go run main.go in Terminal:

santae bash

We have 23 printed back to us, which is the value we’ve inserted into our table in the previous step, so our query has been a success.

Executing SQL queries in Golang

Next, I'll show you how to do this.

Insert operation

To insert an object into your MySQL table using Go:

  1. Add this code to your main.go file:

package main
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    db, err := sql.Open("mysql", "root:<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("Yay, values added!")
}

2. Run main.go in Terminal, and you'll receive the line “Yay, values added” or what you replaced it with if everything goes well.

Just a reminder: 23 is the value we added to the database table.

Read operation

To read values in a MySQL table using Go:

  1. Add this code to your main.go file:

package main
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
type Testtable2 struct {
    id int `json:"id"`
}
func main() {
    db, err := sql.Open("mysql", "root:<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())
    }
    for results.Next() {
        var testtable2 Testtable2
        err = results.Scan(&testtable2.id)
        if err !=nil {
            panic(err.Error())
        }
        fmt.Println(testtable2.id)
    }
}

2. Replace testtable2, 123begin, and id with respective values for your database table, database name, and the column you want to read.

3. Run main.go in Terminal, and you'll receive the values in the table fields referenced if everything is done right.

In this case, the value returned is 23 since it’s what was inserted into the table.

Update operation

To update a MySQL table using Go:

  1. Add this code to your main.go file:

package main
import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    // Replace with your actual DB credentials
    dsn := "username:password@tcp(127.0.0.1:3306)/yourdbname"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatalf("Error opening DB: %v", err)
    }
    defer db.Close()
    // Check DB connection
    if err := db.Ping(); err != nil {
        log.Fatalf("Error pinging DB: %v", err)
    }
    // Example: Update user email where user_id = ?
    query := "UPDATE users SET email = ? WHERE user_id = ?"
    // Parameters
    newEmail := "newemail@example.com"
    userID := 1
    // Execute the query
    result, err := db.Exec(query, newEmail, userID)
    if err != nil {
        log.Fatalf("Error updating record: %v", err)
    }
    // Affected rows
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        log.Fatalf("Error getting rows affected: %v", err)
    }
    fmt.Printf("Update successful, %d row(s) affected.\n", rowsAffected)
}

2. Replace users, email, and user_id with your table and column names.

3. Run main.go in Terminal.

If everything is done right, the table fields mentioned in the code should be updated as instructed. 

Delete operation

To delete a row from a MySQL table using Go:

  1. Add this code to your main.go file:

package main
import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    // Replace with your actual DB credentials
    dsn := "username:password@tcp(127.0.0.1:3306)/yourdbname"
    db, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatalf("Failed to connect to DB: %v", err)
    }
    defer db.Close()
    // Test the connection
    if err := db.Ping(); err != nil {
        log.Fatalf("Failed to ping DB: %v", err)
    }
    // DELETE statement with placeholder
    query := "DELETE FROM users WHERE user_id = ?"
    // ID of the row to delete
    userID := 1
    // Execute the DELETE query
    result, err := db.Exec(query, userID)
    if err != nil {
        log.Fatalf("Failed to delete record: %v", err)
    }
    // Check how many rows were affected
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        log.Fatalf("Failed to retrieve affected rows: %v", err)
    }
    fmt.Printf("Successfully deleted %d row(s)\n", rowsAffected)
}

2. Run main.go in Terminal.

If everything is set up correctly, the specified row will be deleted from the table.

Read also:

Go MySQL driver issues

When writing code, it’s easy for typos or incorrect commands to sneak in.

One of the most common mistakes is running go run main.go in the wrong folder. Make sure you’re inside the folder that contains your Go project, or the app won’t run.

Use the cd (change directory) command to navigate to the correct folder. A quick trick: just drag and drop the folder into your Terminal window after typing cd, then press Enter.

Also, your Go app won’t run without go.mod and go.sum. Run the ls command in Terminal to check that both files are in your folder. If they’re missing, create them using the commands mentioned in the Getting started section above.

And if you think you’ve run into a real MySQL bug, you can report it directly on MySQL’s official bug report page.

Final thoughts on how to use Go with MySQL

In this tutorial, I walked you through how to connect your Golang app to a MySQL database using the Go MySQL driver. I covered everything from setting up your database and installing the driver to running basic SQL operations like insert, read, update, and delete, all with real, hands-on examples. By now, you should feel confident building Go apps that interact smoothly with MySQL.

Along the way, I used a few tools that made the process easier and more efficient. I wrote and tested code in CodeRunner, kept my snippets organized with SnippetsLab, stored database credentials securely using Secrets 4, and managed my databases with TablePlus. These tools helped streamline the workflow, and they can do the same for you.

All of these apps are available through Setapp, a one-stop productivity platform for Mac users. With Setapp, you get access to 260+ powerful apps for development, time management, file organization, and more. You can try it free for 7 days and see how it fits your workflow.

FAQs

How do I install MySQL for Golang?

To install MySQL for Golang, open the package downloaded from the official MySQL website and follow the instructions in the installation wizard. 

What is the best Go MySQL driver?

The best Go MySQL driver is go-sql-driver/mysq. It's the most widely used MySQL driver for Golang since it’s light, fast, and doesn’t rely on C bindings for its native Go implementation. It enables connections via TCP/IPv4, Unix sockets, and TCP/IPv6, while automatically pooling connections and handling broken ones. 

How do I insert data into MySQL using Golang?

To insert data into MySQL using Golang, add this code to your Go file main.go and run it in Terminal by entering: 

go run main.go: 
package main
import (
    "fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func main() {
    db, err := sql.Open("mysql", "root:<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("Values to add")
}

When you run the Go file, it should return “Values to add” or what you substituted it with.

Why is my Golang MySQL connection failing?

Your Golang–MySQL connection might be failing because the MySQL server isn’t running or accessible, there are errors in your database names or connection values, or your file and folder paths are incorrect or broken.


250+ apps for all your daily tasks.

Sign up to Setapp and try them for free.

Security-tested