go语言 mysql卡死,Go语言MySQL优化
在使用go操作MySQL的時候,不知道為什么特別的慢,大概插入每條數據需要10ms的時間,如果是1w條數據,那么就需要100s(1m40s),這個速度是不能夠接受的。
查了一些資料之后,是我在連接數據庫的時候,執行每個SQL語句都連接了一次數據庫。所以效率非常低。
理想的辦法是創建一個transaction(事務),讓事務執行多個SQL語句,最后再commit或者rollback,完成SQL語句的執行。
database handle type DB
DB is a database handle representing a pool of zero or more underlying connections
…..
The sql package creates and frees connections automatically
準備建立連接func Open,返回db handle
函數原型:func Open(driverName, dataSourceName string) (*DB, error)
官方對這個函數的描述是這樣的:
Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.
Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.
Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.
The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.
也就是說這個函數僅僅是確實了連接數據庫的參數是否寫正確,并不進行數據庫連接。
使用func (*DB) Exec
Go
stmt, err := db.Prepare("insert into")
if err != nil {
fmt.Println("insert db.Prepare err =", err)
}
defer stmt.Close()
_, err = stmt.Exec(num)
if err != nil {
fmt.Println("insert stmt.Exec err =", err)
}
1
2
3
4
5
6
7
8
9
10
stmt,err:=db.Prepare("insert into")
iferr!=nil{
fmt.Println("insert db.Prepare err =",err)
}
deferstmt.Close()
_,err=stmt.Exec(num)
iferr!=nil{
fmt.Println("insert stmt.Exec err =",err)
}
之前我是用這樣的方式連接數據庫的,起初也沒有覺得有什么問題。
但是后面進行實際操作的時候,覺得非常的慢。
db.Prepare()進行一個預處理聲明,然后再用返回的statement去執行。Stmt is a prepared statement
這里每次執行這樣的一個操作,都會去連接一次數據庫,這樣非常消耗時間,效率低下。
開啟一個事務func (*DB) Begin
Go
tx, err := db.Begin()
tx.Exec("insert into")
tx.Commit()
1
2
3
tx,err:=db.Begin()
tx.Exec("insert into")
tx.Commit()
Begin()db會連接一次數據庫,并且開啟一個事務。
使用這個tx(事務)進行一系列的操作,不會去重復連接多次數據庫,
完成一系列的連接之后,再Commit提交該事務。這樣會大大節省連接數據庫的時間。
參考鏈接
喜歡 (2)or分享 (0)
總結
以上是生活随笔為你收集整理的go语言 mysql卡死,Go语言MySQL优化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql的dml全,MySQL数据管理
- 下一篇: matlab计算每个细胞面积,手把手教你