下载mysql驱动
$ go get github.com/go-sql-driver/mysql
或者下载源码放到GOPATH中,下载地址:https://github.com/go-sql-driver/mysql
Example
建表
简单创建一个table tbl_log包含3各字段ip,name, detail_msg.
下面代码向表中插入一条记录。
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
var DB *sql.DB
var dataBase = "root:[email protected](127.0.0.1:3306)/new_portal?loc=Local&parseTime=true"
func Init() {
var err error
DB, err = sql.Open("mysql", dataBase)
if err != nil {
log.Fatalln("open db fail:", err)
}
DB.SetMaxOpenConns(20)
DB.SetMaxIdleConns(15)
err = DB.Ping()
if err != nil {
log.Fatalln("ping db fail:", err)
}
}
func main() {
Init()
insert()
}
func insert() {
origin := "abc"
log.Println("orign:",origin)
detailMsg := origin
sql := fmt.Sprintf(
"insert into tbl_log(ip, name, detail_msg) values (‘%s‘, ‘%s‘, ‘%s‘)",
"1.1.0.1",
"test.py",
detailMsg,
)
log.Println("sql:", sql)
_, err := DB.Exec(sql)
if err != nil {
log.Println("exec failed:", err, ", sql:", sql)
return
}
}
output
2018/04/06 10:17:00 orign: abc
2018/04/06 10:17:00 sql: insert into tbl_log(ip, name, detail_msg) values (‘1.1.0.1‘, ‘test.py‘, ‘abc‘)
查看数据库,已经插入记录。