首先,在mysql数据库中建立一张表:
CREATE TABLE `t_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT '0',
`name` varchar(32) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
// 需要先安装: go get github.com/go-sql-driver/mysql
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:123@tcp(192.168.10.15:3306)/gamedata_tian?charset=utf8")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
var result sql.Result
result, err = db.Exec("insert into t_test(age, name) values(?,?)", 13, "joe")
if err != nil {
fmt.Println(err)
return
}
lastId, _ := result.LastInsertId()
fmt.Println("新插入记录的ID为", lastId)
var row *sql.Row
row = db.QueryRow("select * from t_test")
var name string
var id, age int
err = row.Scan(&id, &age, &name)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(id, "\t", name, "\t", age)
result, err = db.Exec("insert into t_test(age, name) values(?,?)", 24, "black")
var rows *sql.Rows
rows, err = db.Query("select * from t_test")
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
var name string
var id, age int
rows.Scan(&id, &age, &name)
fmt.Println(id, "\t", name, "\t", age)
}
rows.Close()
db.Exec("truncate table t_test")
}