如何计算C#中我的SQLite阅读器中返回的行数?

ade*_*ena 11 c# sqlite

我正在使用Microsoft Visual C#2008 Express和SQLite.

我用这样的东西查询我的数据库:

SQLiteCommand cmd = new SQLiteCommand(conn);

cmd.CommandText = "select id from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
SQLiteDataReader reader = cmd.ExecuteReader();
Run Code Online (Sandbox Code Playgroud)

然后我做这样的事情:

if (reader.HasRows == true) {
    while (reader.Read()) {
        // I do stuff here
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是我执行"reader.Read()" 之前计算行数,因为返回的数字将影响我想要/需要做的事情.我知道我可以在while语句中添加一个计数,但我真的需要知道计数.

有什么建议?

Eri*_*ric 26

DataReader延迟运行,因此在开始之前它不会获取整个行集.这有两个选择:

  1. 迭代并计算
  2. 算在SQL语句中.

因为我更像是一个SQL人员,所以我会在SQL语句中进行计数:

cmd.CommandText = "select count(id) from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
int RowCount = 0;

RowCount = Convert.ToInt32(cmd.ExecuteScalar());

cmd.CommandText = "select id from myTable where word = '" + word + "';";
SQLiteDataReader reader = cmd.ExecuteReader();

//...
Run Code Online (Sandbox Code Playgroud)

注意我如何计算*,而不是开头的id.这是因为count(id)将忽略id,而count(*)将只忽略完整的null行.如果你没有空id,那么使用count(id)(它的速度稍快一些,具体取决于你的表大小).

更新:更改为ExecuteScalar,并根据注释计数(id).

  • 这与问题没有直接关系,但我建议不要使用字符串连接来构建sql字符串,而是使用参数化查询来防止可能的sql注入. (5认同)
  • 哦 - "id"永远不会为空.如果是的话,还有别的错误.:) (3认同)