2016-02-26 93 views
0

我有一些我用C#編寫的代碼來更新表。雖然代碼運行時不會產生錯誤,但表格不會更新。C#SQL更新語句不更新

如果我使用SQL命令並在SSMS查詢窗口中運行,它確實有效。

下面的代碼:

 try 
     { 

      string connectionString = "Server=XXXX;Database=XXX;Integrated Security=True"; 

      using (SqlConnection connection = new SqlConnection(connectionString)) 
      using (SqlCommand command = connection.CreateCommand()) 
      { 
       command.CommandText = "update address set central_phone_number = '" + NewPhoneNumber + "'" + " where id = " + ID; 

       connection.Open(); 

       int result = command.ExecuteNonQuery(); 

       connection.Close(); 
      } 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show(ex.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 

id是表所以只有特定行被更新的主鍵。

+0

您的查詢看起來像在執行之前的樣子嗎?什麼是你的專欄類型?順便說一句,你應該總是使用[參數化查詢](http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/)。這種字符串連接對於[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻擊是開放的。 –

+0

'ExecuteNonQuery'方法返回一個數字,表示它所影響的行數。你檢查了結果變量嗎,它是0嗎?如果是這樣,那麼你的'where'子句只是不匹配任何行。具體來說,'ID'是什麼?內容是什麼?你正在執行的最終SQL是什麼? –

+0

在你做任何事情之前,你需要閱讀,理解並開始使用參數化查詢。此代碼易受sql注入攻擊。 –

回答

2

顯然,由於您將id與您的查詢字符串連接起來,因此id是您程序中的字符串。 但是,數據庫中的id數據類型是int。您將通過使用參數簡單地解決您的問題(以及注射等其他問題):

using (SqlCommand command = connection.CreateCommand()) 
{ 
command.CommandText = "update address set central_phone_number [email protected] where id = @ID"; 
command.Parameters.AddWithValue("@num", NewPhoneNumber); 
command.Parameters.AddWithValue("@ID",ID); 
.... 
+2

請注意這裏。使用AddWithValue時,可能會在使用像這樣的傳遞查詢時誤解數據類型。這裏最好指定數據類型。 http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/無論是來自我的+1。 –

+0

'因爲你連接id與你的查詢字符串,id是你的程序中的字符串不正確。沒有顯式調用'ToString'就可以連接一個'int' –