英文:
Db delete query always returns true
问题
我正在使用golang和postgres。我想通过传入用户的ID来从我的表中删除用户。当我运行下面的代码时,我总是得到true。即使我传入一个在表中不存在的ID。这正常吗?如果用户ID不在数据库中,DB.Exec会返回err吗?
func DeleteUser(ID int){
err = nil
_, err := DB.Exec("DELETE FROM Users WHERE user_id=$1", ID)
if err == nil {
return true
}
return false
}
DB.Exec函数在执行SQL语句时,如果出现错误,会返回一个非空的err。所以如果用户ID在数据库中不存在,DB.Exec应该返回一个非空的err。
英文:
I am using golang with postgres. I want to delete users from my table by passing in the Id for that user. When I run the code below I always get true. Even when I pass in a ID that does not exist in the table. Is that normal? Does DB.Exec return err if the user ID is not in the database?
func DeleteUser(ID int){
err = nil
_, err := DB.Exec("DELETE FROM Users WHERE user_id=$1", ID)
if err == nil {
return true
}
return false
}
答案1
得分: 7
尝试这样做
func DeleteUser(ID int){
err = nil
res, err := DB.Exec("DELETE FROM Users WHERE user_id=$1", ID)
if err == nil {
count, err := res.RowsAffected()
if err == nil {
/* 检查 count 并返回 true/false */
}
}
return false
}
英文:
Try this
func DeleteUser(ID int){
err = nil
res, err := DB.Exec("DELETE FROM Users WHERE user_id=$1", ID)
if err == nil {
count, err := res.RowsAffected()
if err == nil {
/* check count and return true/false */
}
}
return false
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论