If you’re working on a project in Go, you often need a database to store information. MySQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your MySQL database with Go.
In order for Go projects to interact with a MySQL database, you’ll need to install and import a MySQL adapter. There are multiple options, but the most widely used MySQL driver for Go is currently Go-SQL-Driver. Navigate to your project directory and then add Go-SQL-Driver to your Go modules:
go get github.com/go-sql-driver/mysql
Then, in your main.go
file, import the go-sql-driver/mysql
package along with database/sql
and fmt
:
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
You’ll need to have your MySQL credentials. You can use this guide to find your credentials.
Once you have your credentials, declare the following constants for your connection credentials, and build a connection string:
const (
host = "localhost"
port = 3306
user = "myUser"
password = "myPassword"
dbname = "myDB"
)
connString := fmt.Sprintf(“%s:%s@tcp(%s:%s)/%s”,
user, password, host, port, dbname)
We can then use sql.Open()
to validate our connection string and create an sql.DB
object:
db, err := sql.Open(“mysql”, connString)
if err != nil {
panic(err)
}
defer db.Close()
And finally, we’ll open up a connection to the database using Ping()
:
err = db.Ping()
if err != nil {
panic(err)
}
Once you have established your connection, you can query your MySQL database from Go. To create and run a query, use Query()
for SELECT statements like this:
myResult, err := db.Query(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”)
if err != nil {
panic(err)
}
defer myResult.Close()
You can also pass variables to Query() for both text and values parameters like this:
text := “SELECT * FROM Users WHERE username = ?”
values := “arctype”
myResult, err := db.Query(text, values)
Now that you’ve connected MySQL to your Go project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up MySQL with Arctype in this tutorial.