How to Connect to MySQL in Golang

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.


Hello, fellow Go programmers! Today, we’re going to explore the world of connecting to MySQL in Golang. MySQL is a popular open-source relational database management system that is widely used in web applications. In this article, we’ll show you how to connect to MySQL in Golang and explore some of the best practices for working with databases. So, let’s get started!

First, let’s start with the basics. To connect to MySQL in Golang, we’ll need to use a MySQL driver. There are several MySQL drivers available for Golang, but one of the most popular is the go-sql-driver/mysql driver. We install this driver using the following command:

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

Once we have the driver installed, we use it to connect to a MySQL database. Here’s an example:

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Connect to the database
    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/mydatabase")
    if err != nil {
        fmt.Println(err)
        return
    }

    // Close the database connection when we're done
    defer db.Close()

    // Perform a query
    rows, err := db.Query("SELECT * FROM users")
    if err != nil {
        fmt.Println(err)
        return
    }

    // Loop through the results and print them to the console
    for rows.Next() {
        var id int
        var name string
        var email string
        err := rows.Scan(&id, &name, &email)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("id=%d, name=%s, email=%s\n", id, name, email)
    }

    // Check for errors after iterating over the results
    err = rows.Err()
    if err != nil {
        fmt.Println(err)
        return
    }
}

This code connects to a MySQL database using the sql.Open() function and performs a query to retrieve all rows from a users table. We use the rows.Next() function to loop through the results and print them to the console. We also check for errors using the rows.Err() function after iterating over the results.

But that’s not all! Golang’s database/sql package provides many other useful functions for working with databases, such as prepared statements and transactions. With these powerful features, we can write efficient and scalable database applications in Golang.

Conclusion

Connecting to MySQL in Golang is a powerful and essential feature for any developer working with databases. With the syntax and functions we’ve explored in this article, you’ll be able to connect to and work with MySQL databases in Golang with ease. So, let’s get connecting with Golang and MySQL!


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!