我用的驱动是:https://github.com/Go-SQL-Driver/MySQL

理由跟 https://github.com/astaxie/build-web-application-with-golang/blob/master/05.2.md 的一样。

比较新,更新维护的比较好;
完全支持database/sql接口
支持keepalive,保持长连接。

安装

$ go get github.com/go-sql-driver/mysql

数据库连接语句

import "database/sql"
import _ "github.com/go-sql-driver/mysql" 

db, e := sql.Open("mysql", "user:password@/dbname?charset=utf8")

代码例子:来自 https://github.com/astaxie/build-web-application-with-golang/blob/master/05.2.md
使用的数据表:

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 DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;

代码:

package main

import(
    "database/sql"
    "fmt"
    _"github.com/go-sql-driver/mysql"
)

func main(){
    db,err:=sql.Open("mysql","root:root@tcp(localhost:8889)/ghj1976test?charset=utf8")
    checkErr(err)

    //插入数据
    stmt,err:=db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
    checkErr(err)

    res,err:=stmt.Exec("ghj1976","RD部门","2013-03-18")
    checkErr(err)

    res,err=stmt.Exec("astaxie","RD部门","2012-12-09")
    checkErr(err)

    id,err:=res.LastInsertId()
    checkErr(err)

    fmt.Println(id)

    //修改数据
    stmt,err=db.Prepare("update user info set username=? where uid=?")
    checkErr(err)

    res,err=stmt.Exec("astaxieupdate",id)
    checkErr(err)

    affect,err:=res.RowsAffected()
    checkErr(err)

    fmt.Println(affect)

    //搜索数据
    rows,err:=db.Query("SELECT * FROM userinfo")
    checkErr(err)

    for rows.Next(){
        var uid int
        var username string
        var department string
        var created string
        err=rows.Scan(&uid,&username,&department,&created)
        checkErr(err)
        fmt.Println(uid)
        fmt.Println(username)
        fmt.Println(department)
        fmt.Println(created)
    }

    //删除数据
    stmt,err=db.Prepare("delete from user info where uid=?")
    checkErr(err)

    res,err=stmt.Exec(id)
    checkErr(err)

    affect,err=res.RowsAffected()
    checkErr(err)

    fmt.Println(affect) 
    db.Close()
}

func checkErr(err error){
    if err!=nil{
        panic(err)
    }
}

db.Prepare()函数用来返回准备要执行的sql操作,然后返回准备完毕的执行状态。
db.Query()函数用来直接执行Sql返回Rows结果。
stmt.Exec()函数用来执行stmt准备好的SQL语句

文档更新时间: 2019-06-07 09:43   作者:月影鹏鹏