我有使SELECT查询的Sqlite方法:

try {
 myConn.Open();

 using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
  sqCommand.CommandText = sql;
  SQLiteDataReader reader = sqCommand.ExecuteReader();
  return reader.GetString(0);
 }
} catch (Exception e) {
 // do exception handling
}


我试图获取最后插入的ID:

sql = 'SELECT id FROM Pacients ORDER BY id DESC LIMIT 1';


我试图像这样

return reader.GetString(0);


它使我失望“没有当前行”异常

最佳答案

调用ExecuteReader之后,您需要调用Read来定位数据集的第一条记录。读取返回true / false,以通知您是否有要读取的记录。因此,您的代码更改为

try {
 myConn.Open();

 using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
  sqCommand.CommandText = sql;
  SQLiteDataReader reader = sqCommand.ExecuteReader();
  if(reader.Read())
     return reader.GetString(0);
  else
     return ""; // or whatever you want to return if no records are present
 }
} catch (Exception e) {
 // do exception handling
}


话虽如此,请记住,如果您只想像查询中那样从一行中仅检索一列,那么最好使用ExecuteScalar而不是ExecuteReader

try {
 myConn.Open();

 using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
  sqCommand.CommandText = sql;
  object result = sqCommand.ExecuteScalar();
  return result != null ? result.ToString() : "";
 }
} catch (Exception e) {
 // do exception handling
}

10-08 02:59