Stop paying for apps you only use sometimes
Setapp gives you 250+ Mac and iOS apps in one subscription. Switch, explore, and get more done — free for 7 days.
TL;DR:
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.
Here are the first steps you need to take:

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.
Create your application in the folder where you have all your Golang installation files, or run:
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").

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:

Next, type go run main.go. Your program will print “Success!” on the screen if everything runs smoothly.
To connect your Go application to MySQL:
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.
Before you set up your MySQL database for Golang, you first need to install MySQL using these steps:
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.

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:

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:

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.
Next, I'll show you how to do this.
To insert an object into your MySQL table using Go:
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.
To read values in a MySQL table using Go:
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.
To update a MySQL table using Go:
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 := "[email protected]"
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.
To delete a row from a MySQL table using Go:
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:
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.
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.
To install MySQL for Golang, open the package downloaded from the official MySQL website and follow the instructions in the installation wizard.
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.
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.
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.