英文:
golang database updating a non-existing entry
问题
我有一个用于更新数据库条目的函数,代码如下所示。逻辑是,更新一个不存在的条目会返回错误。不知道是否有更好的方法来处理错误?谢谢。
func (adb *AppDB) UpdateTicket(t Ticket) error {
result, err := adb.db.NamedExec(`UPDATE ticket SET detail=:detail, start_time=:start_time, end_time=:end_time, priority=:priority WHERE id=:id;`, &t)
if err != nil {
return err
}
nRows, err := result.RowsAffected()
if err != nil {
return err
}
if nRows == 0 {
return fmt.Errorf("Ticket:%s does not exist for update", t)
}
return nil
}
我有一个函数用于更新数据库条目。逻辑是,如果更新一个不存在的条目,会返回错误。我觉得代码在处理错误时有点冗长。是否有更好的方法来处理这个问题?谢谢。
英文:
I have a function to update a database entry as follows. The logic is that updating a non-exisitng entry returns error. Somehow I find the code a bit verbose on error handling. Is there a better way to do this? Thanks.
func (adb *AppDB) UpdateTicket(t Ticket) error {
result, err := adb.db.NamedExec(`UPDATE ticket SET detail=:detail, start_time=:start_time, end_time=:end_time, priority=:priority WHERE id=:id;`, &t)
if err != nil {
return err
}
nRows, err := result.RowsAffected()
if err != nil {
return err
}
if nRows == 0 {
return fmt.Errorf("Ticket:%s does not exist for update", t)
}
return nil
}
答案1
得分: 0
如果你想让代码更简洁易于维护,我强烈推荐使用 ORM。你可以尝试使用 https://github.com/jinzhu/gorm。
对于许多场景来说,命名返回可能会减少冗余,但这并不是最佳实践。
func (adb *AppDB) UpdateTicket(t Ticket) (err error) {
var result ResultType
var nRows int
if result, err = adb.db.NamedExec(`UPDATE ticket SET detail=:detail, start_time=:start_time, end_time=:end_time, priority=:priority WHERE id=:id;`, &t); err != nil {
return
}
if nRows, err = result.RowsAffected(); err != nil {
return
}
if nRows == 0 {
err = fmt.Errorf("Ticket:%s does not exist for update", t)
}
return
}
英文:
If you need to make it less verbose and easy to maintain I would highly recomend using ORM. You may try https://github.com/jinzhu/gorm
Named return might make it less verbose, but this is not a best practise for lot of scenarios
func (adb *AppDB) UpdateTicket(t Ticket) (err error) {
var result ResultType
var nRows int
if result, err = adb.db.NamedExec(`UPDATE ticket SET detail=:detail, start_time=:start_time, end_time=:end_time, priority=:priority WHERE id=:id;`, &t); err != nil {
return
}
if nRows, err = result.RowsAffected(); err != nil {
return
}
if nRows == 0 {
err = fmt.Errorf("Ticket:%s does not exist for update", t)
}
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论