2014-03-28 103 views
1

所以...我不知道这里发生了什么。我有一个变量组保持当前CustomerID和比较的textbox.text更新只是记录......更新即使使用WHERE子句更新所有记录

Dim updateStatement As String = 
    "UPDATE Customers SET " & 
    "Name = """ & txtName.Text & """, " & 
    "Address = """ & txtAddress.Text & """, " & 
    "City = """ & txtCity.Text & """, " & 
    "State = """ & txtState.Text & """, " & 
    "ZipCode = """ & txtZipCode.Text & """" & 
    "WHERE """ & txtCustomerID.Text & """ = """ & customerID & """" 

这里是整个方法的代码:

Private Sub UpdateCustomer() 
    Dim connection As OleDbConnection = MMABooksDB.GetConnection() 
    Dim updateStatement As String = 
    "UPDATE Customers SET " & 
    "Name = """ & txtName.Text & """, " & 
    "Address = """ & txtAddress.Text & """, " & 
    "City = """ & txtCity.Text & """, " & 
    "State = """ & txtState.Text & """, " & 
    "ZipCode = """ & txtZipCode.Text & """" & 
    "WHERE """ & txtCustomerID.Text & """ = """ & customerID & """" 


    Dim updateCommand As New OleDbCommand(updateStatement, connection) 

    Try 
     connection.Open() 
     updateCommand.ExecuteNonQuery() 
     Dim oledbCmd As New OleDbCommand("SELECT @@IDENTITY", connection) 
     Dim customerID As Integer = customerID 
    Catch ex As OleDbException : Throw ex 
    Finally 
     connection.Close() 
    End Try 
End Sub 

所以每当我打接受更新,它更新ALL记录的数据库的...

编辑:是的,我知道这是“坏的编程”不使用参数时,但是这是怎样的中结构想要完成它。

+0

我会对教练......你为什么要教我们陋习,打开自己,SQL注入... – DRapp

+1

你的代码容易受到SQL注入漏洞。请参阅http://technet.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx –

回答

8

的问题是在这里:

"WHERE """ & txtCustomerID.Text & """ = """ & customerID & """" 

假设customerID(无论该变量是)等于同样的事情,在文本框中的ID,这相当于是这样的:

WHERE "1" = "1" 

当然,这总是正确的,所以所有行匹配WHERE子句。你大概意思是这样的:

"WHERE CustomerId = """ & txtCustomerID.Text & """" 

(其中CustomerId是你的ID列的名称),这将是更好的,但是,使用参数,因为你很可能导致SQL注入攻击的方式。

"WHERE CustomerId = @CustomerId" 
+0

我认为它应该是“WHERE customerID =”“”&txtCustomerID.Text&“”“。 ..其中实际的ID来自用户正在使用的客户的文本,但同意参数化查询...糟糕的教练甚至SUGGEST这样的建筑查询 – DRapp

+0

@DRAPP哎呀!谢谢,这就是我的意思。 –