我正在尝试使用 C# SqlDataReader
查找表的计数,但我一直在获取
invalid attempt to read when no data is present
我的代码:
string sql = "SELECT COUNT(*) FROM [DB].[dbo].[myTable]";
SqlCommand cmd = new SqlComman(sql, connectionString);
SqlDataReader mySqlDataReader = cmd.ExecuteReader();
int count = mySqlDataReader.GetInt32(0); // Here is where I get the error.
我知道我有一个有效的数据库连接,因为我可以在很多地方读取和写入它,COUNT(*)
有什么特别之处我无法正确读取它?如何获取要填充的 int count
?
最佳答案
你必须阅读它:
if (mySqlDataReader.Read()) {
count = mySqlDataReader.GetInt32(0);
}
或者,您可以只使用 ExecuteScalar :
int count = (int)cmd.ExecuteScalar();
定义为:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
关于c# - 如何从 SqlDataReader 读取 SQL Server COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19546906/