如何从c#中查找select查询影响的行数

时间:2016-07-30 07:41:36

标签: c# sql-server

我想查找从C#触发select查询时受影响的行数。没有将数据插入数据集或数据表。

string constr = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString; //get connection string Web.config

SqlConnection con = new SqlConnection(constr);

//define Select Query
SqlCommand slct = new SqlCommand("select * From [dbo].[userdetail] where 1=1", con);
int noRows;

//open connection and execute query
con.Open();
noRows = slct.ExecuteNonQuery();
con.Close();

//define Select Query
SqlCommand select = new SqlCommand("select * From [dbo].[userdetail] where 1=0", con);

//open connection and execute query
con.Open();
noRows = select.ExecuteNonQuery();
con.Close();

1 个答案:

答案 0 :(得分:0)

首先,对于您当前的查询使用ExecuteReader()并在阅读下面的循环时保留计数器

int count = 0;

while(rdr.Read())
{
  count++;
}

否则,使用如下的标量查询并使用ExecuteScalar()函数

select count(*) From [dbo].[userdetail] 

SqlCommand cmd = new SqlCommand("select count(*) From [dbo].[userdetail]", con);

// open connection and execute query
con.Open();
int noRows = (int)cmd.ExecuteScalar();