我通过SqlConnection
类连接到数据库。有什么简单的原因要检查数据库中有多少行,还是我必须创建一个SqlDataReader
并递增到其中的最后一行?
问问题
127 次
1 回答
5
我假设“数据库中的行”实际上是指“表中的行”。
你应该使用Count
and SqlCommand.ExecuteScalar
:
int rowCount = 0;
using(var con = new SqlConnection(connectionsString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.TableName", con))
{
try
{
con.Open();
rowCount = (int) cmd.ExecuteScalar();
} catch (Exception ex)
{
// log this exception or do something else useful, otherwise it's better to...
throw;
}
}
于 2013-05-18T23:35:44.720 回答