笔者使用的go的mysql驱动是go-sql-driver, 这个在github上star的比较多,支持database/sql,维护的比较好,
- 代码地址:
https://github.com/go-sql-driver/mysql - 文档地址
https://godoc.org/github.com/go-sql-driver/mysql - 代码示例
https://github.com/go-sql-driver/mysql/wiki/Examples
1. 驱动安装
go get github.com/go-sql-driver/mysql
2. 创建一个测试表
CREATE TABLE `test_userinfo` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(128) DEFAULT NULL,
`user_image` int(11) DEFAULT NULL,
`user_score` double DEFAULT NULL,
`last_modify_time` datetime DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. 测试代码
连接的uri格式
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
第二种是最常用的
// mysql_test project main.go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func err_handler(err error) {
fmt.Printf("err_handler, error:%s\n", err.Error())
panic(err.Error())
}
func test_delete_tb() {
fmt.Println("test delete db")
var sql_uri = "root:123456@/test_db?charset=utf8"
db, err := sql.Open("mysql", sql_uri)
if err != nil {
err_handler(err)
}
defer db.Close()
var delete_sql string = "delete from test_userinfo"
_, err = db.Exec(delete_sql)
if err != nil {
fmt.Printf("try do sql[%s] error[%s]\n", delete_sql)
err_handler(err)
}
}
func test_query() {
fmt.Println("test_query!")
var sql_uri = "root:123456@/test_db?charset=utf8"
db, err := sql.Open("mysql", sql_uri)
if err != nil {
err_handler(err)
}
defer db.Close()
var query_sql string = "select * from test_userinfo"
rows, err := db.Query(query_sql)
if err != nil {
fmt.Printf("try do query_sql[%s] error[%s]\n", query_sql, err.Error())
err_handler(err)
}
// get columns
columns, err := rows.Columns()
if err != nil {
fmt.Printf("try get result set columns error[%s]\n", err.Error())
err_handler(err)
}
for i, colname := range columns {
fmt.Printf("col %d, name: %s\n", i, colname)
}
values := make([]sql.RawBytes, len(columns))
// scan the result set
scan_args := make([]interface{}, len(values))
for i := range values {
scan_args[i] = &values[i]
}
// fetch rows
for rows.Next() {
err = rows.Scan(scan_args...)
if err != nil {
fmt.Printf("try scan rows error[%s].\n", err.Error())
err_handler(err)
}
var value string
for i, col := range values {
if col != nil {
value = string(col)
} else {
value = "NULL"
}
fmt.Printf("col %d = %s\n", i, value)
}
fmt.Printf("---------------------------------\n\n")
}
if err = rows.Err(); err != nil {
fmt.Printf("rows.err [%s]\n", err.Error())
err_handler(err)
}
}
func test_prepare_insert() {
fmt.Println("test_prepare_insert!")
var sql_uri = "root:123456@/test_db?charset=utf8"
db, err := sql.Open("mysql", sql_uri)
if err != nil {
err_handler(err)
}
defer db.Close()
var insert_prepare_sql string = "insert into test_userinfo(user_id, user_name, user_image, user_score, last_modify_time) values(?, ?, ?, ?, now())"
stmt_in, err := db.Prepare(insert_prepare_sql)
if err != nil {
fmt.Printf("try prepare stmt[%s] error[%s]", insert_prepare_sql, err.Error())
err_handler(err)
}
defer stmt_in.Close()
var base_user_id int = 1000
for i := 0; i < 10; i++ {
base_user_id++
user_name := fmt.Sprintf("user_%d", base_user_id)
_, err = stmt_in.Exec(base_user_id, user_name, i, 100+i)
if err != nil {
fmt.Printf("try do prepare exe error[%s]", err.Error())
err_handler(err)
}
}
var query_prepare_sql string = "select user_name, user_image from test_userinfo where user_id = ?"
stmt_out, err := db.Prepare(query_prepare_sql)
if err != nil {
fmt.Printf("try prepare stmt[%s] error[%s]\n", query_prepare_sql, err.Error())
err_handler(err)
}
defer stmt_out.Close()
base_user_id = 1000
var user_name string
var user_image int
for i := 0; i < 12; i++ {
base_user_id++
err = stmt_out.QueryRow(base_user_id).Scan(&user_name, &user_image)
if err != nil {
fmt.Printf("try do query row user_id[%d] error[%s]\n", base_user_id, err.Error())
// err_handler(err)
}
fmt.Printf("res, user_id[%d] => user_name[%s] user_image[%d]\n", base_user_id, user_name, user_image)
}
fmt.Printf("************************************************\n\n")
}
func main() {
test_delete_tb()
test_prepare_insert()
test_query()
}