douzhan8652 2019-06-11 09:10
浏览 57
已采纳

MYSQL并发选择和更新

I can't understand how to select and then update table with several goroutines. In the documentation for db and stmt it says: "is safe for concurrent use by multiple goroutines." Also I use transatcions but without success. I want to start 7 goroutines and take every row.

Data

+--------+-----------+---------------------+
| idTest | someValue | date                |
+--------+-----------+---------------------+
|      1 | 1         | 2019-06-11 11:29:42 |
|      2 | 2         | 2019-06-11 11:29:42 |
|      3 | 3         | NULL                |
|      4 | 4         | NULL                |
|      5 | 5         | NULL                |
|      6 | 6         | NULL                |
|      7 | 7         | NULL                |
+--------+-----------+---------------------+

current code

db, err := sql.Open("mysql", strConn)
if err != nil {
    fmt.Printf("Troubles in connaction! %s", err)
}

var idTest int
var someValue string

stmt, err := db.Prepare("select idTest,someValue from test where date is null limit 1")
CheckError(err)

defer stmt.Close()

rows, err := stmt.Query()
CheckError(err)

defer rows.Close()

for rows.Next() {
    rows.Scan(&idTest, &someValue)

    stmt, err = db.Prepare("update test set date = now() where idTest= ?")
    CheckError(err)
    _, err = stmt.Exec(idTest)
    CheckError(err)
}

Every goroutine have db.conn and sometimes trying to select and update table.

func main() {
    for i := 0; i < 7; i++ {
        dbConn := "blabla"
        go ChildBot(dbConn)
    }
    var input string
    fmt.Scanln(&input)
}
  • 写回答

1条回答 默认 最新

  • duanba4254 2019-06-11 10:43
    关注

    you should read the data and then run a goroutine.

    for rows.Next() {
        rows.Scan(&idTest, &someValue)
        go func(idTest int) {
             stmt, err = db.Prepare("update test set date = now() where idTest= ?")
             CheckError(err)
             _, err = stmt.Exec(idTest)
             CheckError(err)
        }(idTest)
    }
    

    it's done this way because you have to read the data first before doing anything with it. Otherwise, the next read could override your previous value from time to time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分