c# - SQL查询中的C# 捕获计数

如何用 C# (. cs 文件) 从SQL命令中获取计数是最简单的方法


SELECT COUNT(*) FROM table_name



转换为 int 变量?

时间:

使用 SqlCommand.ExecuteScalar() 并将它的强制转换为 int:


cmd.CommandText ="SELECT COUNT(*) FROM table_name";


Int32 count = (Int32) cmd.ExecuteScalar();




SqlConnection conn = new SqlConnection("ConnectionString");


conn.Open();


SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);


Int32 count = (Int32) comm. ExecuteScalar();



你将通过以下方式来转换错误:


cmd.CommandText ="SELECT COUNT(*) FROM table_name";


Int32 count = (Int32) cmd.ExecuteScalar();



改为使用:


string stm ="SELECT COUNT(*) FROM table_name WHERE id="+id+";";


MySqlCommand cmd = new MySqlCommand(stm, conn);


Int32 count = Convert.ToInt32(cmd.ExecuteScalar());


if(count> 0){


 found = true; 


} else {


 found = false; 


}



使用SQL在 C# 中进行补充:


SqlConnection conn = new SqlConnection("ConnectionString");


conn.Open();


SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);


Int32 count = Convert.ToInt32(comm.ExecuteScalar());


if (count> 0)


{


 lblCount.Text = Convert.ToString(count.ToString());//For example a Label


}


else


{


 lblCount.Text ="0";


}


conn.Close();//Remember close the connection




int count = 0; 


using (new SqlConnection connection = new SqlConnection("connectionString"))


{


 sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);


 connection.Open();


 count = (int32)cmd.ExecuteScalar();


}



...