引用
database/sql
_ “github.com/go-sql-driver/mysql”
连接字符串
user:password@/dbname?charset=utf8&parseTime=True&loc=Local
常用方法
sql.Open
sql.Open(“mysql”, 连接字符串)
(db *DB) .Prepare
签名 Prepare(query string) (*Stmt, error)
stmt,err := db.Prepare(`UPDATE users SET time = ? WHERE name = 'pe'`)
defer stmt.Close()
stmt.Exec(time.Now().Unix())
(db *DB) Exec
签名:(query string, args …interface{}) (Result, error)
DB.Exec("insert INTO users(username,password) values(?,?)","test","123456")
DB.Exec("UPDATE users set password=? where id=?","111111",1)
(db *DB) .Query
签名 (query string, args …interface{}) (*Rows, error)
rows, err := DB.Query("select id,username,password from users where id = ?", 2)
for rows.Next() {
//不scan会导致连接不释放
err = rows.Scan(&user.Id, &user.Username, &user.Password)
}
查询单行
row := DB.QueryRow("select id,username,password from users where id=?", 1)
row.Scan(&user.Id,&user.Username,&user.Password)
事务
(db *DB) Begin
tx,_ := db.Begin()
tx.Exec("DELETE FROM USER WHERE uid=?",i)
//
stmt,err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
tx, err := db.Begin()
res, err := tx.Stmt(stmt).Exec(123.45, 98293203)
(tx Tx) Commit()
(tx Tx) Rollback()