1: 首先需要安装MySQL驱动程序(https://github.com/go-sql-driver/mysql)
到项目路径下执行, 获取驱动源码, 编译时该驱动会自动生成
mysql.a
到pkg目录下:
~/gowork$ GOPATH=`pwd` go get github.com/go-sql-driver/mysql
2: 代码结构如下
gaojie@zs-gaojie:~/gowork$ tree
.
├── bin
│ └── main
├── pkg
│ └── linux_amd64
│ └── github.com
│ └── go-sql-driver
│ └── mysql.a
└── src
├── github.com
│ └── go-sql-driver
│ └── mysql
│ ├── buffer.go
│ ├── connection.go
│ ├── const.go
│ ├── driver.go
│ ├── driver_test.go
│ ├── errors.go
│ ├── infile.go
│ ├── LICENSE
│ ├── packets.go
│ ├── README.md
│ ├── result.go
│ ├── rows.go
│ ├── statement.go
│ ├── transaction.go
│ ├── utils.go
│ └── utils_test.go
└── main
└── mysql.go
10 directories, 19 files
3:mysql.go
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"database/sql"
)
/**
GOPATH=`pwd` go get github.com/go-sql-driver/mysql
*/
const (
mysql_host="*.*.*.*"
mysql_user="root"
mysql_password="mysqladmin"
)
func main(){
fmt.Println("connect MySQL...")
//username:password@protocol(address)/dbname?param=value
db, err := sql.Open("mysql", mysql_user+":"+mysql_password+"@tcp4("+mysql_host+":3306)/test")
if err != nil {
log.Fatal(err)
}
//db销毁毁时, 执行close函数关闭数据库链接(defer块会在函数main执行完,再调用)
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err)
}
log.Print("db:", db)
//插入
iSql := "insert into go (name, age) values (?, ?)"
result, err := db.Exec(iSql, "gaojie", 24);
if err != nil {
log.Fatal(err)
}
log.Print(result.LastInsertId())
//查询
rSQL := "select name, age from go"
rows, err := db.Query(rSQL);
if err != nil {
log.Fatal(err)
}
//遍历行
for rows.Next() {
var name string
var age int
//安装顺序,会把值设置到对应变量中
err = rows.Scan(&name, &age)
//输出
log.Println("name :", name, "\t age :", age)
}
}