The framework call LAMP is very popular on the internet in recent years, and the M is the MySQL. MySQL is famous by its open source, easy to use, so it becomes the database in the back-end of many websites.
There are couple of drivers that support MySQL in Go, some of them implemented database/sql
interface, and some of them use their only interface standards.
- https://github.com/go-sql-driver/mysql supports
database/sql
, pure Go code. - https://github.com/ziutek/mymysql supports
database/sql
and user defined interface, pure Go code. - https://github.com/Philio/GoMySQL only supports user defined interface, pure Go code.
I'll use the first driver in my future examples(I use this one in my projects also), and I recommend you to use this one for following reasons:
- It's a new database driver and supports more features.
- Fully support
databse/sql
interface standards. - Support keepalive, long connection with thread-safe.
In following sections, I'll use same database table structure for different databases, the create SQL as follows:
CREATE TABLE `userinfo` (
`uid` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(64) NULL DEFAULT NULL,
`departname` VARCHAR(64) NULL DEFAULT NULL,
`created` DATE NULL DEFAULT NULL,
PRIMARY KEY (`uid`)
);
The following example shows how to operate database based on database/sql
interface standards.
package main
import (
_ "github.com/go-sql-driver/mysql"
"database/sql"
"fmt"
)
func main() {
db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
checkErr(err)
// insert
stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
checkErr(err)
res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
// update
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)
res, err = stmt.Exec("astaxieupdate", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
// query
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
for rows.Next() {
var uid int
var username string
var department string
var created string
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
// delete
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
Let me explain few important functions:
-
sql.Open()
opens a registered database driver, here the Go-MySQL-Driver registered mysql driver. The second argument is DSN(Data Source Name) that defines information of database connection, it supports following formats:user@unix(/path/to/socket)/dbname?charset=utf8 user:password@tcp(localhost:5555)/dbname?charset=utf8 user:password@/dbname user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
-
db.Prepare()
returns SQL operation that is going to execute, also returns execute status after executed SQL. -
db.Query()
executes SQL and returns Rows result. -
stmt.Exec()
executes SQL that is prepared in Stmt.
Note that we use format =?
to pass arguments, it is for preventing SQL injection.
- Directory
- Previous section: database/sql interface
- Next section: SQLite