2014-11-07 11 views
0

我試圖從我的SQL查詢count()傳遞一個值到c#int Tech_Count,但它顯示不同。如果我只運行查詢計數,它返回3,但在C#中,它顯示-1。這是我的代碼。C#中的Int值與SQL count()值不匹配

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

回答

0

這是因爲ExecuteNonQuery不返回這樣的計數SELECT聲明:

MSDN

對於UPDATE,INSERT和DELETE語句,返回值是 受命令影響的行數。當插入或更新的 表中存在觸發器時,返回值包括受插入或更新操作影響的行的編號 以及受觸發器或觸發器影響的行的編號 。對於所有其他類型的 語句,返回值爲-1。

0

爲什麼使用ExecuteNonQuery如果你實際上正在執行查詢?類中的對象很自我解釋。 ExecuteNonQuery用於更新,刪除和插入,以便返回受影響的行。試試這個關於大小:

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

這也適用。謝謝。 – 2014-11-07 05:53:34