Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从SQL查询捕获计数_C#_Sql_Sql Server - Fatal编程技术网

C# 从SQL查询捕获计数

C# 从SQL查询捕获计数,c#,sql,sql-server,C#,Sql,Sql Server,在C.cs文件中,从SQL命令获取计数的最简单方法是什么 SELECT COUNT(*) FROM table_name 转换为int变量?使用并将其转换为int: cmd.CommandText=从表_name中选择COUNT*; Int32 count=Int32 cmd.ExecuteScalar; 您将获得以下转换错误: cmd.CommandText = "SELECT COUNT(*) FROM table_name"; Int32 count = (Int32) cmd.Exec

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

SELECT COUNT(*) FROM table_name
转换为int变量?

使用并将其转换为int:

cmd.CommandText=从表_name中选择COUNT*; Int32 count=Int32 cmd.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

是的,这里的例子也几乎涵盖了这一点,只需将INSERT INTO更改为SELECT语句。在这种情况下,始终会有int类型的返回值。在更一般的情况下,您可能会得到DBNull的返回值,例如,从表1中选择ssn,其中company_id='112233'。由于无法将DBNull强制转换为返回数据类型,因此必须在SQL或应用程序中对其进行测试和更改。@SearchForKnowledge Check返回的值是可以转换为Int32的值。很有可能您正试图转换一个单词。@SearchForKnowledge尝试使用convert.ToInt32cmd.ExecuteScalar而不是cast.use long而不是int作为返回类型。这与我的答案不一样吗?为了清楚起见,连接字符串通常是一个包含有关您连接到哪个数据库的信息的字符串。例如:Server=myServerAddress;数据库=myDataBase;Trusted_Connection=True;这将使用您在计算机上运行的相同凭据将您登录到数据库。我有一个问题。。。如果我想使用文本框在字符串上的什么位置,例如:-string stm=从表_name中选择COUNT*,其中name=+name.Text.Trim+;
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();
}