连接池学习

This commit is contained in:
2025-08-15 03:53:51 +08:00
parent 0844abb869
commit c69251cc26
6 changed files with 194 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
package goroutine
import (
"database/sql"
"fmt"
"math/rand"
"time"
)
func Dataread(db *sql.DB, donetitle chan struct{}) {
// 启动一个长事务(整个循环在一个事务内,而非每次查询一个事务)
tx, err := db.Begin()
if err != nil {
panic(err)
}
defer tx.Rollback() // 确保退出时回滚(仅为测试)
// 随机种子(保持不变)
rand.Seed(time.Now().UnixNano())
// 只执行两次查询,方便观察结果
for i := 0; i < 2; i++ {
select {
case <-time.After(2 * time.Second): // 第一次查询后等待2秒给Datawrite插入时间
var count int
err = tx.QueryRow("SELECT count(*) FROM article WHERE age > 50 FOR UPDATE ").Scan(&count)
if err != nil {
panic(err)
}
fmt.Printf("第%d次查询 count: %d\n", i+1, count)
case <-donetitle:
return
}
}
}

View File

@@ -0,0 +1,11 @@
package goroutine
import "database/sql"
func DataUpdate(db *sql.DB) {
_, err := db.Begin()
if err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,45 @@
package goroutine
import (
"database/sql"
"fmt"
"github.com/google/uuid"
"math/rand"
"strconv"
"time"
)
func Datawrite(db *sql.DB, donetitle chan struct{}) {
timetick := time.Tick(1 * time.Second)
rand.Seed(time.Now().UnixNano())
for {
select {
case <-timetick:
uid, error := uuid.NewRandom()
if error != nil {
panic(error)
}
tx, err := db.Begin()
if err != nil {
panic(err)
}
fmt.Println("开始事务")
_, err = tx.Exec(`insert INTO article (uid,content,author,age) values (?,?,?,?)`, uid, "123", "用户"+strconv.Itoa(rand.Intn(1000)), rand.Intn(40)+60)
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
panic("回滚失败: " + rbErr.Error())
}
panic("插入失败: " + err.Error()) // 明确错误类型
}
err = tx.Commit()
if err != nil {
panic(err)
}
fmt.Println("插入数据成功")
case <-donetitle:
return
}
}
}