连接数据库是语言运用的基本功,mysql是最常见的数据库之一。
驱动包的安装
驱动开源地址https://github.com/go-sql-driver/mysql
安装方法:
$ go get -u github.com/go-sql-driver/mysql
建立测试数据库
CREATE DATABASE archmage;
use archmage;
CREATE TABLE `userinfo` (
`uid` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(64) NULL DEFAULT NULL,
`departname` VARCHAR(64) NULL DEFAULT NULL,
`created` DATE NULL DEFAULT NULL,
PRIMARY KEY (`uid`)
)
CREATE TABLE `userdetail` (
`uid` INT(10) NOT NULL DEFAULT '0',
`intro` TEXT NULL,
`profile` TEXT NULL,
PRIMARY KEY (`uid`)
)
golang连接mysql并执行sql
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var (
dbhostsip = "127.0.0.1:3306"//IP地址
dbusername = "root"//用户名
dbpassword = "123456"//密码
dbname = "archmage"//表名
)
func main() {
db, err := sql.Open("mysql", dbusername+":"+dbpassword+"@tcp("+dbhostsip+")/"+dbname+"?charset=utf8")
checkErr(err)
defer db.Close()
//插入数据
stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
checkErr(err)
res, err := stmt.Exec("archmage", "研发部门", "2017-12-24")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
//更新数据
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)
res, err = stmt.Exec("大法师快跑", 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 userinfo where uid=?")
checkErr(err)
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
//*/
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}