我试图打印一些东西,如果根据查询返回的行数大于0:
using (SqlConnection con = new SqlConnection("ConnectionString")){
con.Open();
string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery(); // get the value of the count
if (count > 0)
{
Console.WriteLine("Returned more than 0 rows");
}
else
{
Console.WriteLine("Did not return more than 0 rows");
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
如何找到返回的行数?
即使没有行,您的查询也会返回一行.如果您的WHERE条件不存在任何行,它将返回0
使用SqlCommand.ExecuteScalar方法()
using (var con = new SqlConnection("ConnectionString"))
{
con.Open();
string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
using (var cmd = new SqlCommand(query, con))
{
int rowsAmount = (int)cmd.ExecuteScalar(); // get the value of the count
if (rowsAmount > 0)
{
Console.WriteLine("Returned more than 0 rows");
}
else
{
Console.WriteLine("Did not return more than 0 rows");
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
ScalarValue将返回第一行查询结果的第一列.因此,对于您的查询,这是检索所需信息的更有效方法.
| 归档时间: |
|
| 查看次数: |
4116 次 |
| 最近记录: |