Reputation: 769
I have simple function which updates my db. I use SQLite3 so I use INTEGER
field as bool
.
Here is this function:
func updateDevice(devID int64, videoPath string, active bool) {
stmt, err := db.Prepare("UPDATE Devices SET CurrentVideo=?, Active=? WHERE ID=?")
if err != nil {
log.Fatalf("Error while preparing to update device with ID: %s: %s", devID, err)
}
res, err := stmt.Exec(videoPath, devID, active)
if err != nil {
log.Fatalf("Error while updating device with ID: %s : %s", devID, err)
}
rowsAff, _ := res.RowsAffected()
if rowsAff > 0 {
log.Printf("Successfully update device with ID: %v", devID)
} else {
log.Println("Didn't affect on any row")
}
}
When I set active
to true
I get the message that I successfully updated the device, but when I want to set active
to false
I get this message: Didn't affect on any row
and in a database, I have still old values.
Why when I use false
as active
I can't update this table? What I'm doing wrong?
Upvotes: 0
Views: 74
Reputation: 194
In the exec you have to pass the values in the same order they had for the prepare.
You have this order in the prepare:
CurrentVideo=?, Active=? WHERE ID=?
it seems to me that in the exec you have reversed the "active" and "devID" values.
func updateDevice(devID int64, videoPath string, active bool) {
stmt, err := db.Prepare("UPDATE Devices SET CurrentVideo=?, Active=? WHERE ID=?")
if err != nil {
log.Fatalf("Error while preparing to update device with ID: %s: %s", devID, err)
}
res, err := stmt.Exec(videoPath, active, devID)
if err != nil {
log.Fatalf("Error while updating device with ID: %s : %s", devID, err)
}
rowsAff, _ := res.RowsAffected()
if rowsAff > 0 {
log.Printf("Successfully update device with ID: %v", devID)
} else {
log.Println("Didn't affect on any row")
}
}
try this way.
Upvotes: 2