What is the method for connecting to MySQL in Go?
There are various methods to connect to a MySQL database in Go language, with one common approach being to use a third-party package for connection. One commonly used method is as follows:
- database/sql is a package in Go that provides a generic interface around SQL (structured query language) databases.
- The website for the MySQL driver for Go programming language on GitHub is github.com/go-sql-driver/mysql.
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
- database connection object
db, err := sql.Open("mysql", "user:password@tcp(hostname:port)/database")
if err != nil {
// 处理连接错误
}
defer db.Close()
User is the MySQL username, password is the password, hostname is the MySQL server host name or IP address, port is the MySQL server port number, and database is the name of the database to be connected to.
- Check the connection to the database.
err = db.Ping()
if err != nil {
// 处理连接错误
}
- Once the connection is successfully established, you can then proceed with executing SQL queries or operations. Here is a simple query example:
rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
// 处理查询错误
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
// 处理扫描错误
}
// 处理查询结果
}
if err := rows.Err(); err != nil {
// 处理遍历结果错误
}
The above is a basic method of connecting to MySQL, specific operations and queries can be adjusted according to requirements.