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 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面