安装
go get github.com/go-sql-driver/mysql
初始化
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
var db, _ = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/testmysql")
func init(){
db.SetMaxOpenConns(threadNum)
db.SetMaxIdleConns(threadNum / 2)
}
查询
rows, err := db.Query("select id,title from xx_news where id = ?", 123)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
for rows.Next() {
var (
id int64
title string
)
if err = rows.Scan(&id, &title); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v,%v \n", id, title)
}
插入
stmt, err := db.Prepare(`INSERT INTO xx_news SET title = ?`)
if err != nil {
fmt.Println(err)
}
res, err1 := stmt.Exec("测试标题")
if err1 != nil {
fmt.Println(err1)
}
fmt.Println(res.LastInsertId)
更新
stmt, err := db.Prepare(`UPDATE xx_news SET title = ? WHERE id = ?`)
if err != nil {
fmt.Println(err)
}
res, err1 := stmt.Exec("测试标题",123)
if err1 != nil {
fmt.Println(err1)
}
fmt.Println(res)
文章评论