在C# (.cs文件)中从SQL命令获取计数的最简单方法是什么?
SELECT COUNT(*) FROM table_name
如何将内容转换为int
变量?
在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();
}
long
类型来存储整数(不像某些人可能会认为的那样使用int
)。因此,var count = (int)(long)cmd.ExecuteScalar();
是解决之道。 - Sinatr