Connecting MySQL Database 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.


In this article, we will explore how to connect a MySQL database using the Go programming language. We will cover various aspects of connecting a MySQL database, including the structure of a typical connection, creating a connection object, and executing queries. By the end of this article, you will have a solid understanding of how to connect a MySQL database in Go.



Introduction

Connecting a MySQL database is an essential part of any Go project that involves storing or retrieving data from a database. In this article, we will provide a comprehensive guide on how to connect a MySQL database using Go. We will cover various aspects of connecting a MySQL database, including the structure of a typical connection, creating a connection object, and executing queries.

Structure of a Typical Connection

A typical connection to a MySQL database in Go consists of the following steps:

  1. Importing the necessary packages: We need to import the database/sql package to connect to a MySQL database using Go.
  2. Creating a connection object: We create a connection object by calling the sql.Open() function and passing in the driver name, which is “mysql” for a MySQL database.
  3. Setting up the connection parameters: We set up the connection parameters, such as the hostname, port number, username, password, and database name, using the Set() method of the connection object.
  4. Establishing the connection: We establish the connection to the MySQL database by calling the Ping() method of the connection object.
  5. Executing queries: Once we have established a connection, we can execute queries on the database by calling the Query() or Exec() methods of the connection object.
  6. Closing the connection: When we are done using the database, we close the connection by calling the Close() method of the connection object.

Creating a Connection Object

To create a connection object in Go, we need to import the necessary packages and create a new instance of the sql.DB struct. The sql.Open() function returns an error if there is any problem establishing the connection. We can then use the connection object to execute queries on the database.

package main

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

func main() {
	// create a new instance of sql.DB struct
	db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/mydatabase")
	if err != nil {
		log.Fatalf("error opening database connection: %v\n", err)
	}
	defer db.Close()
}

In the above example, we import the necessary packages and create a new instance of the sql.DB struct using the sql.Open() function. We pass in the driver name (“mysql”), username, password, hostname, port number, and database name as parameters to the function. The _ "github.com/go-sql-driver/mysql" line imports the MySQL driver package.

Executing Queries

Once we have established a connection to the MySQL database, we can execute queries on the database using the Query() or Exec() methods of the connection object. The Query() method returns a result set that we can iterate over to fetch the results. The Exec() method returns an error if there is any problem executing the query.

package main

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

func main() {
	// create a new instance of sql.DB struct
	db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/mydatabase")
	if err != nil {
		log.Fatalf("error opening database connection: %v\n", err)
	}
	defer db.Close()

	// execute a query on the database
	rows, err := db.Query("SELECT * FROM mytable")
	if err != nil {
		log.Fatalf("error executing query: %v\n", err)
	}
	defer rows.Close()

	// iterate over the result set and fetch each row
	for rows.Next() {
		var id int
		var name string
		err := rows.Scan(&id, &name)
		if err != nil {
			log.Fatalf("error scanning row: %v\n", err)
		}
		fmt.Println(id, name)
	}

	// execute a query that does not return any results
	_, err = db.Exec("INSERT INTO mytable (name) VALUES ('John')")
	if err != nil {
		log.Fatalf("error executing query: %v\n", err)
	}
}

In the above example, we execute a SELECT query using the Query() method and iterate over the result set to fetch each row. We then use the Scan() method to extract the values from each row. After that, we execute an INSERT query using the Exec() method and pass in the values for the column as parameters.

Closing the Connection

When we are done using the database, we should close the connection by calling the Close() method of the connection object. This will release any resources associated with the connection and prevent errors from occurring when we try to use it again in the future.

package main

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

func main() {
	// create a new instance of sql.DB struct
	db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/mydatabase")
	if err != nil {
		log.Fatalf("error opening database connection: %v\n", err)
	}
	defer db.Close()

	// execute a query on the database
	rows, err := db.Query("SELECT * FROM mytable")
	if err != nil {
		log.Fatalf("error executing query: %v\n", err)
	}
	defer rows.Close()

	// iterate over the result set and fetch each row
	for rows.Next() {
		var id int
		var name string
		err := rows.Scan(&id, &name)
		if err != nil {
			log.Fatalf("error scanning row: %v\n", err)
		}
		fmt.Println(id, name)
	}

	// execute a query that does not return any results
	_, err = db.Exec("INSERT INTO mytable (name) VALUES ('John')")
	if err != nil {
		log.Fatalf("error executing query: %v\n", err)
	}

	// close the connection to the database
	db.Close()
}

In the above example, we create a new instance of the sql.DB struct using the sql.Open() function and pass in the necessary parameters. We then use the connection object to execute queries on the database, iterate over the result set, and close the connection when we are done using it.

Conclusion

In this article, we have covered how to connect a MySQL database using Go. We have discussed various aspects of connecting a MySQL database, including the structure of a typical connection, creating a connection object, executing queries, and closing the connection. By following these steps, you can establish a connection to a MySQL database in Go and start querying and manipulating data.


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!