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

Ada*_*ski 1 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 & """"
Run Code Online (Sandbox Code Playgroud)

这是整个方法代码:

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
Run Code Online (Sandbox Code Playgroud)

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

编辑:是的我知道在不使用参数时这是"糟糕的编程",但这就是教师希望它完成的方式.

Ste*_*art 8

问题出在这里:

"WHERE """ & txtCustomerID.Text & """ = """ & customerID & """"
Run Code Online (Sandbox Code Playgroud)

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

WHERE "1" = "1"
Run Code Online (Sandbox Code Playgroud)

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

"WHERE CustomerId = """ & txtCustomerID.Text & """"
Run Code Online (Sandbox Code Playgroud)

(CustomerIdID列的名称在哪里)但是,使用参数会好得多,因为它的方式可能会导致SQL注入攻击.

"WHERE CustomerId = @CustomerId"
Run Code Online (Sandbox Code Playgroud)