How to connect to a MySQL database in Go

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


Connecting to a database is a fundamental task that is often required in different programming tasks. So, if you’re looking to learn how to connect to a MySQL database in Golang, you’re in the right place.

Before diving into the code examples, let’s first understand the theory behind connecting to a MySQL database in Golang.

To connect to a MySQL database in Golang, you’ll need to use a database driver. A driver is a library that provides a set of functions to interact with a specific type of database. Golang provides several database drivers for MySQL, including “github.com/go-sql-driver/mysql” and “github.com/ziutek/mymysql/mysql”.

Once you’ve imported the appropriate driver, you’ll need to provide the necessary information to establish a connection to the MySQL database. This information typically includes the server address, port number, database name, username, and password.

Here’s an example:

package main

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

func main() {
    db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/database_name")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Connection successful")
    }
    defer db.Close()
}

In the code above, we import the necessary packages, including the “database/sql” and the MySQL driver package “github.com/go-sql-driver/mysql”. We then use the sql.Open() function to establish a connection to the MySQL database. The first argument to the sql.Open() function is the name of the driver, which in this case is “mysql”. The second argument is the connection string, which includes the server address, port number, database name, username, and password. We then use the fmt.Println() function to print a message indicating whether the connection was successful or not. Finally, we use the defer statement to ensure that the database connection is closed when the program exits.

Another way to connect to a MySQL database in Golang is by using a connection pool. A connection pool is a cache of database connections that can be reused by multiple threads. This can help improve performance by reducing the overhead of opening and closing database connections.

Here’s an example:

package main

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

func main() {
    config := mysql.Config{
        User:   "username",
        Passwd: "password",
        Net:    "tcp",
        Addr:   "127.0.0.1:3306",
        DBName: "database_name",
    }
    db, err := sql.Open("mysql", config.FormatDSN())
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Connection successful")
    }
    defer db.Close()
}

In the code above, we use the mysql.Config struct to set the necessary information for establishing a connection to the MySQL database. We then use the sql.Open() function to create a connection pool with the specified configuration. We use the fmt.Println() function to print a message indicating whether the connection was successful or not. Finally, we use the defer statement to ensure that the database connection is closed when the program exits.

So why would someone want to connect to a MySQL database in Golang? One common use case is for web applications that need to store and retrieve data from a database.

By connecting to a MySQL database, you can perform operations such as inserting, updating, and retrieving data from the database. This can help you build dynamic web applications that require persistent data storage.

In conclusion, connecting to a MySQL database in Golang is a fundamental task that you’ll encounter frequently in your Golang programming journey. By using a database driver and providing the necessary connection information, you can establish a connection to a MySQL database and perform various operations on the data. By using a connection pool, you can improve the performance of your database operations.

I hope you found this tutorial helpful. If you have any questions or comments, please feel free to leave them below.


Questions or comments? Reach out to me


Learn how to leverage the Go Standard Library like a PRO.

I just created a new course, The Go Standard Library, check it out!