从SQL查询中获取计数

66

在C# (.cs文件)中从SQL命令获取计数的最简单方法是什么?

SELECT COUNT(*) FROM table_name

如何将内容转换为int变量?

5个回答

127

使用SqlCommand.ExecuteScalar() 方法并将其强制转换为 int 类型:

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

2
@SearchForKnowledge 检查返回的值是否是可以转换为Int32的值。很有可能你正在尝试将一个单词转换。 - m.edmondson
5
尝试使用Convert.ToInt32(cmd.ExecuteScalar())代替强制转换。 - Willz
谢谢你们两位的帮助 :) - SearchForKnowledge
1
将“使用长整型而不是整型作为返回类型”翻译成中文。仅返回翻译后的文本。 - EKanadily
SQLite使用long类型来存储整数(不像某些人可能会认为的那样使用int)。因此,var count = (int)(long)cmd.ExecuteScalar(); 是解决之道。 - Sinatr
显示剩余4条评论

27
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

3
这不就和我的回答一模一样吗? - m.edmondson
1
仅供澄清,连接字符串通常是包含有关您正在连接的数据库的信息的字符串。例如:“Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;”这将使用与您在计算机上运行的相同凭据登录到数据库。 - erikric

10

以下情况会导致转换错误:

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; 
}

我有一个问题...如果我想使用文本框在字符串中使用where怎么办? 例如:string stm = "SELECT COUNT(*) FROM table_name WHERE name="+Name.Text.Trim()+";" ; - Bishoy Frank

3

使用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

0
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接