如何使用sqCommand.ExecuteReader();?返回数据

时间:2017-11-11 15:53:18

标签: c# sqlite

我有使用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);

它让我失去了“没有当前行”的例外

1 个答案:

答案 0 :(得分:2)

调用ExecuteReader后,需要在数据集的第一条记录上调用Read to position。读取返回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
}