How to Use Go with MySQL?


MySQL is a popular open-source relational database management system that is widely used in modern web applications. Go, on the other hand, is a fast and efficient programming language that is becoming increasingly popular for building web applications. In this article, we will discuss how to use Go with MySQL, including how to connect to a MySQL database and how to perform basic CRUD operations.

Installing the MySQL Driver for Go

Before we can start using Go with MySQL, we need to install the MySQL driver for Go. The easiest way to do this is by using the following command −

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

This command will download and install the MySQL driver for Go, which we will use to connect to our MySQL database.

Connecting to a MySQL Database

To connect to a MySQL database using Go, we first need to create a database object. We can do this using the following code −

db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/mydb")
if err != nil {
   log.Fatal(err)
}

In this code, we are creating a MySQL database object by specifying the username, password, and database name. We then use the sql.Open() function to connect to the database, passing in the MySQL driver name as the first parameter.

Performing CRUD Operations

Once we have connected to our MySQL database using Go, we can start performing basic CRUD operations. The following code demonstrates how to insert a new record into a MySQL table −

stmt, err := db.Prepare("INSERT INTO users(name, email) VALUES(?,?)")
if err != nil {
   log.Fatal(err)
}

res, err := stmt.Exec("John", "john@example.com")
if err != nil {
   log.Fatal(err)
}

id, err := res.LastInsertId()
if err != nil {
   log.Fatal(err)
}

fmt.Println("Inserted record with ID:", id)

In this code, we are creating a prepared statement object using the db.Prepare() function. We then use the stmt.Exec() function to execute the prepared statement, passing in the values for the new record. Finally, we use the res.LastInsertId() function to get the ID of the newly inserted record.

Conclusion

In conclusion, using Go with MySQL is a straightforward process that can be accomplished using the official MySQL driver for Go. By following the steps outlined in this article, you can connect to a MySQL database using Go and perform basic CRUD operations, such as inserting records into a table. As you become more familiar with Go and MySQL, you can use these tools to build complex web applications that can scale to meet the needs of your users.

Updated on: 26-Apr-2023

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements