0

my queries

var m sync.Mutex
m.Lock()
defer m.Unlock()

_, err1 := database.Exec(`UPDATE  UserData SET coins = coins + ? WHERE rollno = ?`, transfer_data.Coins, transfer_data.ReceiverRollno)    
if err1 != nil {
   //if some error rollback databse to initial condition and print the error 
   fmt.Println("error lies in database.Exec() err1")
   fmt.Println(err1)
   tx.Rollback()
   return
   // panic(err)
}
    
_, err2 := database.Exec(`UPDATE UserData SET coins = coins - ?  WHERE rollno = ? AND coins - ? >= 0`, transfer_data.Coins, claims.Rollno, transfer_data.Coins)
    
if err2 != nil {
   //if some error rollback databse to initial condition and print the error
   fmt.Println(err2)
   fmt.Println("error lies in database.Exec() err2")
   tx.Rollback()
   return
}

//we are here so this means transaction is successful so Commit this change to the database
tx.Commit()

my table

UserCoin_info := `CREATE TABLE IF NOT EXISTS UserData(
   "rollno" INTEGER NOT NULL,
   "coins" INTEGER NOT NULL
);`
    
statement, err := db.Prepare(UserCoin_info)
if err != nil {
   panic(err)
}
statement.Exec()

I am getting database lock error as err1 while making a update in the first query, i tried using mutexes but still getting this error, i searched for possible solutions but didn't get any.

1 Answers1

0

Database lock is result of not closing *Stmt and *Rows.

statement, err := db.Prepare(UserCoin_info)
if err != nil {
     panic(err)
}
defer statement.Close()

statement.Exec()

  • to read also https://stackoverflow.com/a/32483180/4466350 and this is another variation https://stackoverflow.com/a/37769626/4466350 –  Jul 26 '21 at 09:53