Home:ALL Converter>MYSQL concurrency select and update

MYSQL concurrency select and update

Ask Time:2019-06-11T17:10:03         Author:Alina

Json Formatter

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)
}

Author:Alina,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56540212/mysql-concurrency-select-and-update
yy