2015-12-30 85 views
-4

嘗試插入訪問數據庫時,INSERT INTO語句中出現語法錯誤。發生錯誤的代碼片段是:INSERT INTO語句中的vb.net語法錯誤

If (checkBox.IsChecked) Then 
     cmd.CommandText = "INSERT INTO Participants([Full Name],[From],[Gender],[Category],[Event],[Weight],[DOB],[Age]) VALUES(" + textBox.Text + "," + textBox_Copy2.Text + "," + gender + "," + comboBox.SelectedItem.ToString + "," + "Kata" + "," + textBox_Copy.Text + "," + dp.Text + "," + textBox_Copy1.Text 
     cmd.ExecuteNonQuery() 
    End If 
    If (checkBox_Copy2.IsChecked) Then 
     cmd.CommandText = "INSERT INTO Participants([Full Name],[From],[Gender],[Category],[Event],[Weight],[DOB],[Age]) VALUES(" + textBox.Text + "," + textBox_Copy2.Text + "," + gender + "," + comboBox.SelectedItem.ToString + "," + "Kumite" + "," + textBox_Copy.Text + "," + dp.Text + "," + textBox_Copy1.Text 
     cmd.ExecuteNonQuery() 
    End If 
    If (checkBox_Copy1.IsChecked) Then 
     cmd.CommandText = "INSERT INTO Participants([Full Name],[From],[Gender],[Category],[Event],[Weight],[DOB],[Age]) VALUES(" + textBox.Text + "," + textBox_Copy2.Text + "," + gender + "," + comboBox.SelectedItem.ToString + "," + "Team Kata" + "," + textBox_Copy.Text + "," + dp.Text + "," + textBox_Copy1.Text 
     cmd.ExecuteNonQuery() 
    End If 
    If (checkBox_Copy.IsChecked) Then 
     cmd.CommandText = "INSERT INTO Participants([Full Name],[From],[Gender],[Category],[Event],[Weight],[DOB],[Age]) VALUES(" + textBox.Text + "," + textBox_Copy2.Text + "," + gender + "," + comboBox.SelectedItem.ToString + "," + "Team Kumite" + "," + textBox_Copy.Text + "," + dp.Text + "," + textBox_Copy1.Text 
     cmd.ExecuteNonQuery() 
    End If 
+1

從語法錯誤的一部分,如果用戶檢查所有4個複選框,你確定要插入4條記錄嗎? – Steve

+2

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 您應該**不**將您的SQL語句連接在一起 - 使用**參數化查詢**代替以避免SQL注入 –

+0

另請參閱[DRY原則](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) – Plutonix

回答

3

對於文本字段,您必須將引號中的值放在VALUES子句中。注意,在這個例子中

"INSERT INTO Participants([Full Name]) VALUES ('" + textBox.Text + "')" 

單引號但是你會好得多使用參數,而不是把正確的值在SQL語句中。看到這個 https://msdn.microsoft.com/en-us/library/tyy0sz6b(v=vs.110).aspx

相關問題