我正在使用golang-postgres进行工作:
"database/sql"
_ "github.com/lib/pq"
我在做什么:
我运行了一个选择查询。如果在选择时没有找到任何条目,我会继续插入一个。否则,更新或其他操作...
问题是,每次插入返回ErrNoRows("sql: no rows in result set"),即使我可以在数据库中看到插入成功并添加了一行。
此外,lastInsertID始终保持为0,而如果我在数据库中检查,则具有实际值(例如131)
似乎代码下面的注释2附近的错误被缓存了,并再次显示出来。
// 1. Select first
sQueryStmt, sPrepErr := db.Prepare(selectQuery)
if sPrepErr != nil {
glog.V(3).Infof("selectQuery prepare failed. err: %v", sPrepErr)
return sPrepErr
}
queryErr := sQueryStmt.QueryRow(today, itemID).Scan(&a, &b, &c, &d, &e, &f, &g, &h, &i, &j)
if queryErr != nil {
// 2. Getting ErrNoRows here is expected, for the first entry
if queryErr == sql.ErrNoRows {
glog.V(3).Infof("selectQuery returned no results. err: %v", queryErr)
var lastInsertID int
iQueryStmt, iPrepErr := db.Prepare(insertQuery)
if iPrepErr != nil {
glog.V(3).Infof("insertQuery prepare failed. err: %v", iPrepErr)
return iPrepErr
}
insertErr := iQueryStmt.QueryRow(today, today, today, taskID).Scan(&lastInsertID)
if insertErr != nil {
// 3. Somehow, even after row is correctly being created, I am getting insertErr as "sql: no rows in result set" here
glog.V(3).Infof("insertQuery failed. err: %v", insertErr)
} else {
// control never comes to this part.
glog.V(3).Infof("insertQuery Successful. lastInsertID: %v", lastInsertID)
}
} else {
glog.V(3).Infof("Couldn't run query on Postgres database. err: %v", queryErr)
return queryErr
}
}
在 database/sql 内部调试时,显示它在下面的代码块中返回了这个错误:
if !r.rows.Next() {
if err := r.rows.Err(); err != nil {
return err
}
return ErrNoRows
}
但每次查询数据库时,数据总是已经被插入。
编辑:
selectQuery = `select task_id, creation_date, times_x_ran,
a_count, b_count, c_count, d_count, e_count
from reports where creation_date = $1 and task_id = $2`
insertQuery = `insert into reports
(creation_date, creation_time, last_modified, task_id, times_x_ran, times_y_ran, a, b, c, d, e, x_errors, y_errors)
values
($1, $2, $3, $4,
1, 0,
0, 0, 0, 0, 0,
'', '' )`