日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

go语言 mysql卡死,Go语言MySQL优化

發布時間:2025/3/20 数据库 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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优化的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。