vb.net
2014-10-09 124 views -4 likes 
-4

我面臨着使用vb.net更新Microsoft Access數據庫的問題,顯示錯誤是更新語句中的語法錯誤我無法找到我錯過的東西來檢測錯誤可以幫助我們解決錯誤。更新語句中的語法錯誤ms訪問

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 & "'" 

回答

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參數。這將增加可讀性,並防止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 [email protected]_id, " & _ 
      "  [email protected]_name, " & _ 
      "  [email protected], " & _ 
      "  [email protected], " & _ 
      "  [email protected], " & _ 
      "  [email protected]_time, " & _ 
      "  [email protected]_class, " & _ 
      "  [flight charges][email protected] charges, " & _ 
      "  [email protected]" & _ 
      "WHERE flight_id = @flight_id'" 

始終使用使用語句,以確保該連接處置propertly_

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 
+0

我修復[飛行Chrages]爲[Flight_Charges]但我仍得到相同錯誤語法錯誤在更新陳述 – 2014-10-09 14:43:12

+0

@AshuRenu:你見過我已經eidted我的答案? – 2014-10-09 14:45:45

+0

當我使用你的代碼,我在這一行中得到錯誤:使用con作爲新的OleDbConnection(「連接字符串」) – 2014-10-09 14:58:32

1

你真的應該吐出t他提出的疑問,看看你生產什麼,而不是在原始代碼只是盯着:

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

這將產生

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

我看不到您的建議代碼請再次輸入,請確認 – 2014-10-09 14:29:11

+0

是否真的?你不知道如何添加一個空間到你的字符串? – 2014-10-09 14:33:40

+0

不,我不能對不起 – 2014-10-09 14:45:16

相關問題