【发布时间】:2021-04-17 11:59:24
【问题描述】:
在 C#(.cs 文件)中从 SQL 命令获取计数的最简单方法是什么
SELECT COUNT(*) FROM table_name
到int 变量中?
【问题讨论】:
标签: c# sql sql-server
在 C#(.cs 文件)中从 SQL 命令获取计数的最简单方法是什么
SELECT COUNT(*) FROM table_name
到int 变量中?
【问题讨论】:
标签: c# sql sql-server
使用SqlCommand.ExecuteScalar() 并将其转换为int:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
【讨论】:
INSERT INTO 更改为您的SELECT 语句..
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;
}
【讨论】:
在 C# 中使用 SQL 进行补充:
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();
}
【讨论】: