Files
2025-08-15 03:53:51 +08:00

36 lines
840 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}
}
}