2016-02-26 92 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' –