更新记录时,AddWithValue不起作用

时间:2016-04-05 05:18:10

标签: mysql vb.net

我有这段代码

    MySQL_Query = "UPDATE `owner_info` " _
    & "SET first_name=" & first_name _
    & ", last_name= " & last_name _
    & ", middle_name=" & middle_name _
    & ", address= " & address _
    & ", contact_num= " & contact_num _
    & " WHERE id=" & ownerID

    Console.WriteLine(MySQL_Query)

    Dim MySQL_CMD As New MySqlCommand(MySQL_Query, MysqlConn)
    With frmOwner_Edit
        If String.IsNullOrEmpty(first_name) = True Then first_name = .lblExisting_FirstName.Text
        If String.IsNullOrEmpty(last_name) = True Then last_name = .lblExisting_LastName.Text
        If String.IsNullOrEmpty(middle_name) = True Then middle_name = .lblExisting_MiddleName.Text
        If String.IsNullOrEmpty(address) = True Then address = .lblExisting_Address.Text
        If String.IsNullOrEmpty(contact_num) = True Then contact_num = .lblExisting_ContactNum.Text
    End With
    Try
        MySQL_CMD.Connection.Open()
        'MySQL_CMD.CommandText = MySQL_Query
        MySQL_CMD.ExecuteNonQuery()
    Catch myerror As MySqlException
        Console.WriteLine("Error: Owner Info Insert")
        Console.WriteLine(myerror)
    Finally
        MysqlConn.Close()
        MysqlConn.Dispose()
    End Try

并且正常工作,我正在尝试应用AddWithValue但它不起作用?我觉得我在这里错过了一些东西。这是代码。

    MySQL_Query = "UPDATE `owner_info` " _
    & "SET first_name='@first_name', last_name='@last_name', middle_name='@middle_name', address='@address', contact_num='@contact_num' " _
    & "WHERE id='@id'"
    Dim MySQL_CMD As New MySqlCommand(MySQL_Query, MysqlConn)
    With frmOwner_Edit
        If String.IsNullOrEmpty(first_name) = True Then first_name = .lblExisting_FirstName.Text
        If String.IsNullOrEmpty(last_name) = True Then last_name = .lblExisting_LastName.Text
        If String.IsNullOrEmpty(middle_name) = True Then middle_name = .lblExisting_MiddleName.Text
        If String.IsNullOrEmpty(address) = True Then address = .lblExisting_Address.Text
        If String.IsNullOrEmpty(contact_num) = True Then contact_num = .lblExisting_ContactNum.Text
    End With
    Try
        MySQL_CMD.Connection.Open()
        MySQL_CMD.CommandText = MySQL_Query
        MySQL_CMD.Parameters.AddWithValue("@first_name", first_name)
        MySQL_CMD.Parameters.AddWithValue("@last_name", last_name)
        MySQL_CMD.Parameters.AddWithValue("@middle_name", middle_name)
        MySQL_CMD.Parameters.AddWithValue("@address", address)
        MySQL_CMD.Parameters.AddWithValue("@contact_num", contact_num)
        MySQL_CMD.Parameters.AddWithValue("@id", ownerID)
        MySQL_CMD.ExecuteNonQuery()
    Catch myerror As MySqlException
        Console.WriteLine("Error: Owner Info Insert")
        Console.WriteLine(myerror)
    Finally
        MysqlConn.Close()
        MysqlConn.Dispose()
    End Try

1 个答案:

答案 0 :(得分:1)

移除params周围的蜱虫。当它们在那里时MySql将它们视为字符串而不是参数。所以错误就是不提供它需要的参数。