前言:对于c#和MySql,我对MySqlConnector很陌生。
我想要实现的目标是执行查询,然后使用FOUND_ROWS获取SqlDataReader中返回的记录数。
以下是我正在运行的代码:
public MySqlDataReader Execute()
{
RecordCount = 0;
mCommand = new MySqlCommand("SELECT a,b,c FROM TABLE my_table where field_x=hello", connection);
MySqlCommand result_count_cmd = new MySqlCommand("Select FOUND_ROWS()", mCommand.Connection);
try
{
// create mysql command and execute it
mReader = mCommand.ExecuteReader();
// get the number of rows returned by the query
RecordCount = Convert.ToInt32(result_count_cmd.ExecuteScalar());
}
catch (Exception ex)
{
Console.WriteLine("Error Running Query: " + mCommand.CommandText);
Console.WriteLine(ex.ToString());
}
return mReader;
}
我面临的问题是,在尝试执行FOUND_ROWS()查询时,它无法告诉我无法在另一个非封闭式读取器使用的同一连接上创建新的DataReader。这听起来很公平,有没有办法可以检索查询返回的行数WITHOUT,运行与SELECT COUNT [...]完全相同的查询作为不同的DB操作?或者有没有办法在DataReader打开时调用FOUND_ROWS查询?
答案 0 :(得分:1)
编辑:
try
{
// create mysql command and execute it
mReader = mCommand.ExecuteReader();
int RecordCount=0;
while (mReader.Read())
{
///do what you want with the result
RecordCount++; //count number of rows returned
}
}