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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值