GO - SQL接口方法 [包 - database/sql]

  1. [SQL, 操作方法]
  2. Open() creates a DB, 打开一个database handle
  3. # 并不会去获得数据库连接有效性,当执行数据库操作的时候才会去连接
  4. # 通过Ping()来测试, 连接的有效性
  5. Close() - closes the DB
  6. Query() - 查询
  7. QueryRow() -查询行
  8. Exec() -执行操作,updateinsertdelete
  9. Row - A row is not a hash map, but an abstraction of a cursor
  10. Next()
  11. Scan()

详细说明

[安装MYSQL驱动包 - Go-SQL-Driver/MySQL]

    :go get github.com/Go-SQL-Driver/MySQL     # 下载

  :go install github.com/Go-SQL-Driver/MySQL # 安装

[导入包]

import "database/sql"
import _"github.com/Go-SQL-Driver/MySQL"
# "_", 引入该包,只调用该包里面的init函数,初始化了里面的变量

[连接数据库]

    :db, err := sql.Open("mysql", "用户名:密码@tcp(IP:端口)/数据库?charset=utf8")

  # db, err := sql.Open("mysql", "root:111111@tcp(127.0.0.1:3306)/test?charset=utf8")

    // user@unix(/path/to/socket)/dbname?charset=utf8
    // user:password@tcp(localhost:3306)/dbname?charset=utf8
    // user:password@/dbname
    // user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname

[增删改查]

# 表结构
CREATE TABLE `userinfo` (
      `uid` int(10) NOT NULL AUTO_INCREMENT,
      `username` varchar(64) DEFAULT NULL,
      `departname` varchar(64) DEFAULT NULL,
      `created` date DEFAULT NULL,
      PRIMARY KEY (`uid`)
   ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

# 增

    :01 Exec函数
    result, err := db.Exec("INSERT INTO userinfo (username, departname, created)
      VALUES (?, ?, ?)","lily","销售","2016-06-21")

    :Prepare获得stmt,然后调用Exec添加
  stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
    res, err := stmt.Exec("zhja", "研发", "2016-06-17")

  :id, err := res.LastInsertId() # 获得刚刚添加数据的自增ID

# 删

    :INSERT语句改为DELETE语句

# 改

    :INSERT语句改为UPDATE语句

# 查

    :01 查询单条数据,QueryEow 函数
  var username, departname, created string
 err := db.QueryRow("SELECT username,departname,created FROM userinfo WHERE uid=?", 3)
         .Scan(&username, &departname, &created)

  :02 查询多条数据,并遍历 - Query 获取数据,for xxx.Next() 遍历数据
  rows, err := db.QueryRow("SELECT * FROM userinfo WHERE uid=?", 3)
  for rows.Next {
      var username,departname,created string
    if err:= rows.Scan(&username, &departname, &created); err==nil {
        fmt.Println(err)
    }
    fmt.Println(username)
    fmt.Println(departname)
    fmt.Println(created)
  }

# 事务

    :tx, err := db.Begin() # 操作数据库之前执行

  :err := tx.Commit() # 保存到数据库

  :err := tx.Rollback() # 回滚

程序案例

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/Go-SQL-Driver/MySQL"
)

// 定义数据结构
type vehicle struct {
    id     string
    userId string
}

// 检测并处理错误
func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {

    db, err := sql.Open("mysql", "root:uyEQOdoD-T715h6@tcp(rm-bp10h4rjh8q877420lo.mysql.rds.aliyuncs.com:3306)/sinoinfo?charset=utf8")
    // 测试连接的有效性
  err = db.Ping()
    if err != nil {
    // 打印LOG日志
    log.Println(err)
    }

    checkErr(err)

    // 01 查询单条数据
    var id, userId string
    err = db.QueryRow("SELECT id,user_id as userId FROM vehicle WHERE id=?", "V116993").Scan(&id, &userId)
    fmt.Println(id)
    fmt.Println(userId)

    // 02 查询多行数据
    //rows, err := db.Query("SELECT id, user_id as userId FROM vehicle WHERE user_id=?", "A102806")
    //checkErr(err)
    //for rows.Next() {
    //    var id, userId string
    //    // 获取数据
    //    if err := rows.Scan(&id, &userId); err != nil {
    //        fmt.Println(err)
    //    }
    //    v := vehicle{id, userId}
    //    fmt.Println(v)
    //}

    // 03 insert
    //// 构造插入SQL
    //stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
    //checkErr(err)
    //// 填充参数, 并执行
    //res, err := stmt.Exec("zhja", "研发", "2016-06-17")
    //checkErr(err)
    //// 获取插入数据的主键 id
    //id, err := res.LastInsertId()
    //checkErr(err)
    //fmt.Println(id)

    //// 02 直接插入数据
    //result, err := db.Exec("INSERT INTO userinfo (username, departname, created) VALUES (?, ?, ?)", "lily", "销售", "2016-06-21")
    //checkErr(err)
    //
    //ids, err := result.LastInsertId()
    //fmt.Println(ids)
    //
    //// 03 删除数据
    //db.Exec("DELETE FROM userinfo WHERE uid=?", 1)
    //checkErr(err)
    //
    //stmt, err := db.Prepare("DELETE FROM userinfo WHERE uid=?")
    //stmt.Exec(2)

    // 03 事务处理
    // 开启事务
    //tx, err := db.Begin()
    //checkErr(err)
    //
    // 执行SQL
    //stmt, err1 := tx.Prepare("INSERT INTO userinfo (username, departname, created) VALUES (?, ?, ?)")
    //checkErr(err1)
    //_, err2 := stmt.Exec("test", "测试", "2016-06-20")
    //checkErr(err2)
    //
    //// 提交事务
    ////err3 := tx.Commit()
    //
    //// 事务回滚
    //err3 := tx.Rollback()
    //checkErr(err3)
}