How to Use Go with MySQL?
To use Go with MySQL, we need to follow the below steps:
- Install MySQL driver for Go: We need to install the MySQL driver for Go to connect to the MySQL database. We can install it using the following command:
go get -u github.com/go-sql-driver/mysql
- Import the MySQL driver: After installing the MySQL driver, we need to import it in our Go code using the following import statement:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
- Connect to the MySQL database:
To connect to the MySQL database, we need to create a new instance of the
sql.DB
struct using theOpen()
method of thesql
package. We need to pass the MySQL driver name and the MySQL connection string to theOpen()
method. The MySQL connection string should contain the MySQL username, password, host, port, and database name. Here is an example:
db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname")
if err != nil {
log.Fatal(err)
}
defer db.Close()
- Execute SQL queries:
After connecting to the MySQL database, we can execute SQL queries using the
Query()
orExec()
method of thesql.DB
struct. Here is an example:
rows, err := db.Query("SELECT * FROM users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
Alternatively, we can use the Prepare()
method of the sql.DB
struct to prepare a SQL statement and then execute it using the Query()
or Exec()
method of the sql.Stmt
struct. Here is an example:
stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
res, err := stmt.Exec("John")
if err != nil {
log.Fatal(err)
}
lastInsertId, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
fmt.Println("Last insert ID:", lastInsertId)