即使使用WHERE子句,更新也会更新所有记录

时间:2014-03-28 17:10:21

标签: sql vb.net

所以......我不知道这里发生了什么。我有一个变量集,它包含CURRENT customerID,并与textbox.text进行比较以更新该记录......

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

每当我点击接受更新时,它都会更新数据库的所有记录......

编辑:是的,我知道在不使用参数时这是“糟糕的编程”,但教师希望这样做。

1 个答案:

答案 0 :(得分:8)

问题在于:

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

假设customerID(无论该变量是什么)与文本框中的ID相同,它等同于:

WHERE "1" = "1"

当然,这总是正确的,因此所有行都匹配WHERE子句。你可能意味着:

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

(其中CustomerId是您的ID列的名称)但是,使用参数会好得多,因为您拥有它的方式可能会导致SQL注入攻击。

"WHERE CustomerId = @CustomerId"