C# C中的Int值与SQL count()值不匹配

C# C中的Int值与SQL count()值不匹配,c#,sql-server,C#,Sql Server,我试图将一个值从我的SQL查询计数传递到c int Tech_计数,但它显示的不同。如果我只运行查询计数,它返回3,但在c中,它显示为-1。这是我的密码 SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True; AttachDbFilename=C:\Users\anthonyhau\Documents\Lawn Mower\LawnMowerData

我试图将一个值从我的SQL查询计数传递到c int Tech_计数,但它显示的不同。如果我只运行查询计数,它返回3,但在c中,它显示为-1。这是我的密码

        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True; AttachDbFilename=C:\Users\anthonyhau\Documents\Lawn Mower\LawnMowerDatabase\LawnMowerDatabase\Database1.mdf");
        con.Open();
        SqlCommand cmd1 = new SqlCommand("update Tech set Customer_Count = (select IdAndCnt.cnt from (select Tech_Id,count (Tech_id) as cnt from Customers group by Tech_Id ) as IdAndCnt where Tech.Tech_Id = IdAndCnt.Tech_Id)", con);
        SqlCommand cmd = new SqlCommand("INSERT INTO Customers (First_Name, Last_Name, Street, City, State, Zip, Phone, Date_Started) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', '" + textBox6.Text + "', '" + textBox7.Text + "', '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "')", con);
        SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);

        cmd1.ExecuteNonQuery();
        cmd.ExecuteNonQuery();
        int Tech_Count = techcnt.ExecuteNonQuery();

        textBox8.Text = Tech_Count.ToString();


        con.Close();

我认为您必须使用ExecuteScalar而不是ExecuteOnQuery,它将解决您的问题

int Tech_Count=inttechcnt.ExecuteScalar

这是因为ExecuteOnQuery不会像SELECT语句那样返回计数:

对于UPDATE、INSERT和DELETE语句,返回值为 受命令影响的行数。当触发器存在于 在插入或更新表时,返回值包括数字 受插入或更新操作和编号影响的行数 受一个或多个触发器影响的行数。对于所有其他类型的 语句,返回值为-1


如果您实际上正在执行查询,为什么要使用ExecuteOnQuery??类中的对象是非常自解释的。ExecuteOnQuery用于更新、删除和插入,以便返回受影响的行。试试这个尺码:

SqlCommand techcnt = new SqlCommand("Select @count:=count(Tech_Id) From Tech", con);
techcnt.Parameters.Add("@count", SqlDbType.Int).Direction = ParameterDirection.Output;
techcnt.CommandType = CommandType.Text;
techcnt.ExecuteScalar();
textBox8.Text = techcnt.Parameters["@count"].Value.ToString();
或者像这样短一些的:

SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);

textBox8.Text = techcnt.ExecuteScalar().ToString();