Home  >  Article  >  Database  >  How to use Go with MySQL?

How to use Go with MySQL?

WBOY
WBOYforward
2023-09-15 09:25:021202browse

如何将 Go 与 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 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.

Install MySQL driver for Go

Before we start using Go and MySQL, we need to install the MySQL driver for Go. The easiest way is to use the following command:

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

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

Connect to 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 create a MySQL database object by specifying the username, password, and database name. We then connect to the database using the sql.Open() function, passing in the MySQL driver name as the first argument.

Perform CRUD operations

Once we connect to the MySQL database using Go, we can start performing basic CRUD operations. The following code demonstrates how to insert new records 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 use the db.Prepare() function to create a prepared statement object. We then execute the prepared statement using the stmt.Exec() function, passing in the value of the new record. Finally, we use the res.LastInsertId() function to get the ID of the newly inserted record.

in conclusion

In summary, using Go with MySQL is a simple process and can be accomplished using Go’s official MySQL driver. Following the steps outlined in this article, you can use Go to connect to a MySQL database 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.

The above is the detailed content of How to use Go with MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete