//MYSQL需要引入 _ "github.com/go-sql-driver/mysql"
执行安装:
go get -u github.com/mattn/go-sqlite3
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
创建数据库,创建表
//打开数据库,如果不存在,则创建
db, err := sql.Open("sqlite3", "./test.db")
checkErr(err)
//创建表
sql_table := `
CREATE TABLE IF NOT EXISTS userinfo(
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(64) NULL,
departname VARCHAR(64) NULL,
created DATE NULL
);
`
db.Exec(sql_table)
执行Sql语句
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("wangshubo", "国务院", "2017-04-21")
checkErr(err)
查询sql语句
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
var uid int
var username string
var department string
var created time.Time
for rows.Next() {
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
rows.Close()
异常处理
func checkErr(err error) {
if err != nil {
panic(err)
}
}