建立测试数据表
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL DEFAULT '',
`age` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
上代码
package main
import (
// sql.DB 是接口协议,具体的DB操作是通过driver执行
// 但是不能通过driver直接操作,需要通过接口操作,此处匿名引入,自动注册初始化到sql.DB中
_ "github.com/go-sql-driver/mysql"
"database/sql"
"fmt"
)
/**
* DB 连接池
*/
type DBWorker struct {
Dsn string
Db *sql.DB
}
// 对应数据表字段
type userTB struct {
Id int
Name sql.NullString // 数据类型设置为 NullXXX,以便读取时判断是否赋值
Age sql.NullInt64
}
func main() {
var err error
dbw := DBWorker{
// 格式大概为:user:password@protocol(ip:port)/database?charset=utf8
Dsn: "root:XXXXXX(@tcp(localhost:3307)/test?charset=utf8",
}
dbw.Db, err = sql.Open("mysql", dbw.Dsn)
if err != nil {
panic(err)
return
}
defer dbw.Db.Close()
dbw.insertData()
dbw.queryData()
}
// 插入数据测试
func (dbw* DBWorker) insertData() {
stmt, _ := dbw.Db.Prepare(`INSERT INTO user (name, age) VALUES (?, ?)`)
defer stmt.Close()
ret, err := stmt.Exec("虚无缥缈", 23)
if err != nil {
fmt.Printf("insert data error:%v\n", err)
return
}
if LastInsertId, err := ret.LastInsertId(); err == nil {
fmt.Printf("LastInsertId %d\n", LastInsertId)
}
if RowsAffected, err := ret.RowsAffected(); err == nil {
fmt.Printf("RowsAffected %d\n", RowsAffected)
}
}
// 查询数据测试
func (dbw *DBWorker) queryData() {
stmt, _ := dbw.Db.Prepare("SELECT * FROM user WHERE age >= ? and age < ?")
defer stmt.Close()
user := userTB{}
rows, err := stmt.Query(20, 30)
defer rows.Close()
if err != nil {
fmt.Printf("query data error : %v\n", err)
return;
}
for rows.Next() {
// SCAN赋值的顺序需要与拉取出来的数据一一对应
// 建表时是 id,name,age,此处赋值相对应的为Id, Name, Age
err = rows.Scan(&user.Id, &user.Name, &user.Age)
if err != nil {
fmt.Printf("scan error : %v\n", err)
continue
}
// 运行为空的情形下,给赋值默认值
if !user.Name.Valid {
user.Name.String = ""
}
// 运行为空的情形下,给赋值默认值
if !user.Age.Valid {
user.Age.Int64 = 0
}
fmt.Println("id: ", user.Id, " name: ", user.Name.String, " age: ", int(user.Age.Int64))
}
err = rows.Err()
if err != nil {
fmt.Printf("rows.Err: %v", err)
}
}
运行结果
LastInsertId 7
RowsAffected 1
id: 1 name: a age: 25
id: 5 name: 石义波 age: 23
id: 6 name: 石义波 age: 23
id: 7 name: 虚无缥缈 age: 23
Process finished with exit code 0
结束语
有疑问加站长微信联系(非本文作者)