Go語言官方沒有實現MySQL數據庫驅動,經常使用的開源MySQL數據庫驅動實現以下:
(1)Go MySQL Driver
Go MySQL Driver支持database/sql接口,所有采用Go語言實現。
官方網站:
https://github.com/go-sql-driver/mysql/
(2)MyMySQL
MyMySQL支持database/sql接口,也支持自定義的接口,所有采用Go語言實現。
官方網站:
https://github.com/ziutek/mymysql
(3)GoMySQL
GoMySQL不支持database/sql接口,採用自定義接口,所有采用Go語言實現。
官方網站:
https://github.com/Philio/GoMySQLmysql
Go-MySQL-Driver優勢:
(1)維護比較好。
(2)徹底支持database/sql接口。
(3)支持keepalive,保持長鏈接。
Go-MySQL-Driver安裝以下:go get github.com/go-sql-driver/mysql
導入包:git
import "database/sql" import _ "github.com/go-sql-driver/mysql"
登陸MySQL數據庫,建立數據庫create database student default character set utf8;
github
func Open(driverName, dataSourceName string) (*DB, error)
driverName參數爲數據庫驅動名稱。
dataSourceName是鏈接參數,參數格式以下:
user:password@tcp(host:port)/dbname?charset=utf8sql
func (db *DB) Prepare(query string) (*Stmt, error)
Prepare爲後續查詢或執行操做建立一個準備SQLfunc (s *Stmt) Exec(args ...interface{}) (Result, error)
使用給定參數執行準備的SQL語句func (s *Stmt) Query(args ...interface{}) (*Rows, error)
使用給定參數執行準備的SQL查詢語句func (db *DB) Exec(query string, args ...interface{}) (Result, error)
執行SQL操做,query爲SQL語句,能夠接收可變參數,用於填充SQL語句的某些字段值。func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
執行SQL查詢操做,能夠接收多個參數數據庫
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func errorHandler(err error) { if err != nil { fmt.Println(err.Error()) } } var ( CREATE_TABLE = "CREATE TABLE student(" + "sid INT(10) NOT NULL AUTO_INCREMENT," + "sname VARCHAR(64) NULL DEFAULT NULL," + "age INT(10) DEFAULT NULL,PRIMARY KEY (sid))" + "ENGINE=InnoDB DEFAULT CHARSET=utf8;" ) // 創建數據庫鏈接 func setupConnect() *sql.DB { db, err := sql.Open("mysql", "root:xxxxxx@tcp(118.24.159.133:3306)/student?charset=utf8") errorHandler(err) return db } // 建立表 func CreateTable(db *sql.DB, sql string) { _, err := db.Exec(sql) errorHandler(err) } var INSERT_DATA = `INSERT INTO student(sid,sname,age) VALUES(?,?,?);` // 插入數據 func Insert(db *sql.DB) { db.Exec(INSERT_DATA, 1, "唐僧", 30) } var UPDATE_DATA = `UPDATE student SET age=28 WHERE sname="唐僧";` // 修改數據 func Update(db *sql.DB) { db.Exec(UPDATE_DATA) } var DELETE_DATA = `DELETE FROM student WHERE age>=30` // 刪除記錄 func Delete(db *sql.DB) { db.Exec(DELETE_DATA) } var DELETE_TABLE = `DROP TABLE student;` // 刪除表 func DeleteTable(db *sql.DB) { db.Exec(DELETE_TABLE) } var QUERY_DATA = `SELECT * FROM student;` // 查詢數據 func Query(db *sql.DB) { rows, err := db.Query(QUERY_DATA) if err != nil { fmt.Println(err) } for rows.Next() { var name string var id int var age int if err := rows.Scan(&id, &name, &age); err != nil { fmt.Println(err) } fmt.Printf("%s is %d\n", name, age) } } func main() { // 創建數據鏈接 db := setupConnect() // 建立數據庫表 CreateTable(db, CREATE_TABLE) // 插入數據 Insert(db) // 查詢數據 Query(db) // 刪除數據 Delete(db) // 插入數據 Insert(db) // 修改數據 Update(db) // 查詢數據 Query(db) // 刪除表 DeleteTable(db) // 關閉數據庫鏈接 db.Close() }
func (db *DB) Begin() (*Tx, error)
開啓事務,從鏈接池中取出一個*TX
類型鏈接。使用TX類型鏈接能夠進行回滾事務和提交事務。func (tx *Tx) Commit() error
提交事務func (tx *Tx) Rollback() error
回滾func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)
執行SQL操做func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)
執行SQL查詢操做安全
// 支持事務回滾機制的批量數據插入 func MultiInsert(db *sql.DB) { // 批量數據插入 tx, err := db.Begin() if err != nil { fmt.Println(err) } values := [][]interface{}{{2, "孫悟空", 500}, {3, "豬八戒", 200}, {4, "沙悟淨", 100}} stmt, err := tx.Prepare("INSERT INTO student(sid,sname,age) VALUES(?,?,?);") for _, val := range values { _, err := stmt.Exec(val...) if err != nil { fmt.Printf("INSERT failed:%v", err) tx.Rollback() } } tx.Commit() }
func sql.Open(driverName, dataSourceName string) (*DB, error)
sql.Open返回一個DB對象,DB對象對於多個goroutines併發使用是安全的,DB對象內部封裝了鏈接池。Open函數並無建立鏈接,只是驗證參數是否合法,而後開啓一個單獨goroutine去監聽是否須要創建新的鏈接,當有請求創建新鏈接時就建立新鏈接。func (db *DB) Exec(query string, args ...interface{}) (Result, error)
執行不返回行(row)的查詢,好比INSERT,UPDATE,DELETE
DB交給內部的exec方法負責查詢。exec會首先調用DB內部的conn方法從鏈接池裏面得到一個鏈接。而後檢查內部的driver.Conn是否實現了Execer接口,若是實現了Execer接口,會調用Execer接口的Exec方法執行查詢;不然調用Conn接口的Prepare方法負責查詢。func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
用於查詢,DB交給內部的query方法負責查詢。query首先調用DB內部的conn方法從鏈接池裏面得到一個鏈接,而後調用內部的queryConn方法負責查詢。func (db *DB) Prepare(query string) (*Stmt, error)
返回一個Stmt。Stmt對象能夠執行Exec,Query,QueryRow等操做。DB交給內部的prepare方法負責查詢。prepare首先調用DB內部的conn方法從鏈接池裏面得到一個鏈接,而後調用driverConn的prepareLocked方法負責查詢。func (db *DB) Begin() (*Tx, error)
開啓事務,返回Tx對象。調用Begin方法後,TX會與指定的鏈接綁定,一旦事務提交或者回滾,事務綁定的鏈接就還給DB的鏈接池。DB交給內部的begin方法負責處理。begin首先調用DB內部的conn方法從鏈接池裏面得到一個鏈接,而後調用Conn接口的Begin方法得到一個TX。
進行MySQL數據庫操做時,若是每次SQL操做都從DB對象的鏈接池中獲取鏈接,則會在很大程度上損耗效率。所以,必須儘可能在一個鏈接上執行SQL操做。併發
package main import ( "database/sql" "fmt" "strconv" "time" _ "github.com/go-sql-driver/mysql" ) var db = &sql.DB{} func init() { db, _ = sql.Open("mysql", "root:xxxxxx@tcp(118.24.159.133:3306)/student?charset=utf8") CREATE_TABLE := "CREATE TABLE student(" + "sid INT(10) NOT NULL AUTO_INCREMENT," + "sname VARCHAR(64) NULL DEFAULT NULL," + "age INT(10) DEFAULT NULL,PRIMARY KEY (sid))" + "ENGINE=InnoDB DEFAULT CHARSET=utf8;" db.Exec(CREATE_TABLE) } func update() { //方式1 update start := time.Now() for i := 1001; i <= 1100; i++ { db.Exec("UPDATE student set age=? where sid=? ", i, i) } end := time.Now() fmt.Println("db.Exec update total time:", end.Sub(start).Seconds()) //方式2 update start = time.Now() for i := 1101; i <= 1200; i++ { stm, _ := db.Prepare("UPDATE student set age=? where sid=? ") stm.Exec(i, i) stm.Close() } end = time.Now() fmt.Println("db.Prepare 釋放鏈接 update total time:", end.Sub(start).Seconds()) //方式3 update start = time.Now() stm, _ := db.Prepare("UPDATE student set age=? where sid=?") for i := 1201; i <= 1300; i++ { stm.Exec(i, i) } stm.Close() end = time.Now() fmt.Println("db.Prepare 不釋放鏈接 update total time:", end.Sub(start).Seconds()) //方式4 update start = time.Now() tx, _ := db.Begin() for i := 1301; i <= 1400; i++ { tx.Exec("UPDATE student set age=? where sid=?", i, i) } tx.Commit() end = time.Now() fmt.Println("tx.Exec 不釋放鏈接 update total time:", end.Sub(start).Seconds()) //方式5 update start = time.Now() for i := 1401; i <= 1500; i++ { tx, _ := db.Begin() tx.Exec("UPDATE student set age=? where sid=?", i, i) tx.Commit() } end = time.Now() fmt.Println("tx.Exec 釋放鏈接 update total time:", end.Sub(start).Seconds()) } func delete() { //方式1 delete start := time.Now() for i := 1001; i <= 1100; i++ { db.Exec("DELETE FROM student WHERE sid=?", i) } end := time.Now() fmt.Println("db.Exec delete total time:", end.Sub(start).Seconds()) //方式2 delete start = time.Now() for i := 1101; i <= 1200; i++ { stm, _ := db.Prepare("DELETE FROM student WHERE sid=?") stm.Exec(i) stm.Close() } end = time.Now() fmt.Println("db.Prepare 釋放鏈接 delete total time:", end.Sub(start).Seconds()) //方式3 delete start = time.Now() stm, _ := db.Prepare("DELETE FROM student WHERE sid=?") for i := 1201; i <= 1300; i++ { stm.Exec(i) } stm.Close() end = time.Now() fmt.Println("db.Prepare 不釋放鏈接 delete total time:", end.Sub(start).Seconds()) //方式4 delete start = time.Now() tx, _ := db.Begin() for i := 1301; i <= 1400; i++ { tx.Exec("DELETE FROM student WHERE sid=?", i) } tx.Commit() end = time.Now() fmt.Println("tx.Exec 不釋放鏈接 delete total time:", end.Sub(start).Seconds()) //方式5 delete start = time.Now() for i := 1401; i <= 1500; i++ { tx, _ := db.Begin() tx.Exec("DELETE FROM student WHERE sid=?", i) tx.Commit() } end = time.Now() fmt.Println("tx.Exec 釋放鏈接 delete total time:", end.Sub(start).Seconds()) } func query() { //方式1 query start := time.Now() rows, _ := db.Query("SELECT sid,sname FROM student") defer rows.Close() for rows.Next() { var name string var id int if err := rows.Scan(&id, &name); err != nil { fmt.Println(err) } } end := time.Now() fmt.Println("db.Query query total time:", end.Sub(start).Seconds()) //方式2 query start = time.Now() stm, _ := db.Prepare("SELECT sid,sname FROM student") defer stm.Close() rows, _ = stm.Query() defer rows.Close() for rows.Next() { var name string var id int if err := rows.Scan(&id, &name); err != nil { fmt.Println(err) } } end = time.Now() fmt.Println("db.Prepare query total time:", end.Sub(start).Seconds()) //方式3 query start = time.Now() tx, _ := db.Begin() defer tx.Commit() rows, _ = tx.Query("SELECT sid,sname FROM student") defer rows.Close() for rows.Next() { var name string var id int if err := rows.Scan(&id, &name); err != nil { fmt.Println(err) } } end = time.Now() fmt.Println("tx.Query query total time:", end.Sub(start).Seconds()) } func insert() { //方式1 insert start := time.Now() for i := 1001; i <= 1100; i++ { //每次循環內部都會去鏈接池獲取一個新的鏈接,效率低下 db.Exec("INSERT INTO student(sid,sname,age) values(?,?,?)", i, "student"+strconv.Itoa(i), i-1000) } end := time.Now() fmt.Println("db.Exec insert total time:", end.Sub(start).Seconds()) //方式2 insert start = time.Now() for i := 1101; i <= 1200; i++ { //Prepare函數每次循環內部都會去鏈接池獲取一個新的鏈接,效率低下 stm, _ := db.Prepare("INSERT INTO student(sid,sname,age) values(?,?,?)") stm.Exec(i, "student"+strconv.Itoa(i), i-1000) stm.Close() } end = time.Now() fmt.Println("db.Prepare 釋放鏈接 insert total time:", end.Sub(start).Seconds()) //方式3 insert start = time.Now() stm, _ := db.Prepare("INSERT INTO student(sid,sname,age) values(?,?,?)") for i := 1201; i <= 1300; i++ { //Exec內部並無去獲取鏈接,爲何效率仍是低呢? stm.Exec(i, "user"+strconv.Itoa(i), i-1000) } stm.Close() end = time.Now() fmt.Println("db.Prepare 不釋放鏈接 insert total time:", end.Sub(start).Seconds()) //方式4 insert start = time.Now() //Begin函數內部會去獲取鏈接 tx, _ := db.Begin() for i := 1301; i <= 1400; i++ { //每次循環用的都是tx內部的鏈接,沒有新建鏈接,效率高 tx.Exec("INSERT INTO student(sid,sname,age) values(?,?,?)", i, "user"+strconv.Itoa(i), i-1000) } //最後釋放tx內部的鏈接 tx.Commit() end = time.Now() fmt.Println("tx.Exec 不釋放鏈接 insert total time:", end.Sub(start).Seconds()) //方式5 insert start = time.Now() for i := 1401; i <= 1500; i++ { //Begin函數每次循環內部都會去鏈接池獲取一個新的鏈接,效率低下 tx, _ := db.Begin() tx.Exec("INSERT INTO student(sid,sname,age) values(?,?,?)", i, "user"+strconv.Itoa(i), i-1000) //Commit執行後釋放鏈接 tx.Commit() } end = time.Now() fmt.Println("tx.Exec 釋放鏈接 insert total time:", end.Sub(start).Seconds()) } func main() { insert() query() update() query() delete() } // output: // db.Exec insert total time: 2.069104068 // db.Prepare 釋放鏈接 insert total time: 1.869348813 // db.Prepare 不釋放鏈接 insert total time: 1.447833105 // tx.Exec 不釋放鏈接 insert total time: 1.098540307 // tx.Exec 釋放鏈接 insert total time: 3.465670469 // db.Query query total time: 0.005803479 // db.Prepare query total time: 0.010966584 // tx.Query query total time: 0.011800843 // db.Exec update total time: 2.117122871 // db.Prepare 釋放鏈接 update total time: 2.132430998 // db.Prepare 不釋放鏈接 update total time: 1.523685366 // tx.Exec 不釋放鏈接 update total time: 1.346163272 // tx.Exec 釋放鏈接 update total time: 3.129312377 // db.Query query total time: 0.00848425 // db.Prepare query total time: 0.013472261 // tx.Query query total time: 0.012418198 // db.Exec delete total time: 2.100008271 // db.Prepare 釋放鏈接 delete total time: 1.9821439490000001 // db.Prepare 不釋放鏈接 delete total time: 1.429259466 // tx.Exec 不釋放鏈接 delete total time: 1.103143464 // tx.Exec 釋放鏈接 delete total time: 2.863670582
從示例結果看,執行SQL操做時若是不釋放鏈接,則效率比釋放鏈接要高。tcp