更新语句ms访问中的语法错误

时间:2014-10-09 14:20:47

标签: vb.net

我在使用vb .net更新Microsoft访问数据库时遇到问题,显示错误是更新语句中的语法错误我无法找到我错过了检测错误的内容可以帮助我修复错误。

cmd.CommandText = "UPDATE FLIGHT_DETAILS" & "SET FLIGHT_ID='" & Me.txtFlight_Id.Text &
"',FLIGHT_NAME='" & Me.txtFlight_Name.Text & "',SOURCE='" & Me.txtSource.Text &
 "',DESTINATION='" & Me.txtDestination.Text & "',DEPARTURE='" & Me.txtDeparture.Text &
 "',ARRIVAL_TIME='" & Me.txtArrival_Time.Text & "',FLIGHT_CLASS='" & Me.txtFlight_Class.Text
 & "',FLIGHT CHARGES='" & Me.txtFlight_Charges.Text & "',SEATS='" & Me.txtSeats.Text & "'" &
 " WHERE FLIGHT_ID ='" & Me.txtFlight_Id.Text & "'"

2 个答案:

答案 0 :(得分:1)

你真的应该吐出生成的查询来查看你生成的内容,而不是只是盯着原始代码:

cmd.CommandText = "UPDATE FLIGHT_DETAILS" & "SET FLIGHT_ID='" 
                                        ^^^^^--- no spaces

将生成

UPDATE FLIGHT_DETAILSSET FLIGHT_ID='...
                     ^---no space

答案 1 :(得分:0)

我在UPDATE FLIGHT_DETAILSSET FLIGHT_ID之间至少缺少一个空格。所以:

cmd.CommandText = "UPDATE FLIGHT_DETAILS SET FLIGHT_ID='" & Me.txtFlight_Id.Text ...

你还有一个列flight charges,里面有一个空格,不允许。

使用[flight charges]。但是不要在字段或对象名称中使用空格,因为它简化了事情。

甚至MS Access都支持sql参数。这将增加readabiliy并防止sql注入。

首先,我验证用户输入:

Dim flightId As Int32
If Not Int32.TryParse(txtFlight_Id.Text, flightId) Then
    MessageBox.Show("Enter a valid flightId")
    Return
End If
Dim arrival_time As DateTime
If Not DateTime.TryParse(txtArrival_Time.Text, arrival_time) Then
    MessageBox.Show("Enter a valid arrival_time")
    Return
End If
Dim seats As Int32
If Not Int32.TryParse(txtSeats.Text, seats) Then
    MessageBox.Show("Enter  valid seats")
    Return
End If

现在你可以使用这个漂亮的sql statament而无需通过字符串连接添加参数:

Dim sql = "UPDATE flight_details " & _
          "SET    flight_id=@flight_id, " & _
          "       flight_name=@flight_name,  " & _
          "       source=@source,  " & _
          "       destination=@destination, " & _
          "       departure=@departure,  " & _
          "       arrival_time=@arrival_time,  " & _
          "       flight_class=@flight_class,  " & _
          "       [flight charges]=@flight charges, " & _
          "       seats=@seats" & _
          "WHERE  flight_id = @flight_id'"

始终使用Using语句确保连接属性_

Using con As New OleDbConnection("Connection-String")
    Using cmd As New OleDbCommand(sql, con)
        Dim param = New OleDbParameter("@flight_id", SqlDbType.Int)
        param.Value = flightId
        cmd.Parameters.Add(param)
        param = New OleDbParameter("@flight_name", SqlDbType.VarChar)
        param.Value = Me.txtFlight_Name.Text
        cmd.Parameters.Add(param)
        ' ... '
        Dim updated = cmd.ExecuteNonQuery()
    End Using
End Using