采用https://github.com/go-sql-driver/mysql
下载数据库依赖
go get -u github.com/go-sql-driver/mysql
Go-Mysql
增删改查
package mainimport ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql")func main() { //链接Mysql username:password@/dbname db, err := sql.Open("mysql", "root:@/go?charset=utf8") checkErr(err) // //nil = db // //insertData(* db) //updateData(* db) searchData(* db) deleteData(* db)}//插入数据func insertData(db sql.DB) { stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?") checkErr(err) res, err := stmt.Exec("data", "研发部门", "2012-12-09") checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println(id)}//更新数据func updateData(db sql.DB) { stmt, err := db.Prepare("update userinfo set username=? where uid=?") res, err := stmt.Exec("gg", 1) checkErr(err) affect, err := res.RowsAffected(); fmt.Println(affect);}//查询数据func searchData(db sql.DB) { 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) }}//删除数据func deleteData(db sql.DB) { stmt, err := db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err := stmt.Exec(1); 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
语句