引用

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)

  1. stmt,err := db.Prepare(`UPDATE users SET time = ? WHERE name = 'pe'`)
  2. defer stmt.Close()
  3. stmt.Exec(time.Now().Unix())

(db *DB) Exec

签名:(query string, args …interface{}) (Result, error)

  1. DB.Exec("insert INTO users(username,password) values(?,?)","test","123456")
  2. DB.Exec("UPDATE users set password=? where id=?","111111",1)

(db *DB) .Query

签名 (query string, args …interface{}) (*Rows, error)

  1. rows, err := DB.Query("select id,username,password from users where id = ?", 2)
  2. for rows.Next() {
  3. //不scan会导致连接不释放
  4. err = rows.Scan(&user.Id, &user.Username, &user.Password)
  5. }

查询单行

  1. row := DB.QueryRow("select id,username,password from users where id=?", 1)
  2. row.Scan(&user.Id,&user.Username,&user.Password)

事务

(db *DB) Begin

  1. tx,_ := db.Begin()
  2. tx.Exec("DELETE FROM USER WHERE uid=?",i)

//

  1. stmt,err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  2. tx, err := db.Begin()
  3. res, err := tx.Stmt(stmt).Exec(123.45, 98293203)

(tx Tx) Commit()
(tx
Tx) Rollback()