2013-02-26 195 views
0

我是數據庫連接的新手,當我遇到cmdInsert.ExecuteNonQuery()行的問題時,它說INSERT INTO語句存在語法錯誤,我無法弄清楚問題所在:插入語句中的語法錯誤

Imports System.Data 
Imports System.Data.OleDb 
Public Class txtNotes 
    Dim cnnOLEDB As New OleDbConnection 
    Dim cmdInsert As New OleDbCommand 

    Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\CourseworkDB" 
    'the name of the database goes in here' 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

     cnnOLEDB.ConnectionString = strConnectionString 
     cnnOLEDB.Open() 

    End Sub 

    Private Sub AddFirstName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFirstName.Click 
     If txtFirstName.Text <> "" Then 

      MsgBox(cmdInsert.CommandText) 
      cmdInsert.CommandText = "INSERT INTO Customer (First Name) VALUES (" & txtFirstName.Text & ", '" 
      cmdInsert.CommandType = CommandType.Text 
      cmdInsert.Connection = cnnOLEDB 
      cmdInsert.ExecuteNonQuery() 
     Else 
      MsgBox("Enter the required values:" & vbNewLine & "1. First Name") 
     End If 
     cmdInsert.Dispose() 
    End Sub 
End Class 

回答

0

試試這個

"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"

0

警告:Bobby在看着你。

cmdInsert.CommandText = _ 
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')" 
1

I強烈建議您不要進入構建SQL字符串的例程,通過將字符串串聯在一起。你正在向SQL注入開放,特別是如果這是基於Web的。您應該在字符串中使用佔位符參數構建命令,然後將這些參數添加到命令對象。添加參數相同的順序,因爲它們將出現在命令如

cmdInsert.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES (@parmFirstName, @parmLastName)" 
cmdInsert.Parameters.AddWithValue("@parmFirstName", txtFirstName.Text); 
cmdInsert.Parameters.AddWithValue("@parmLastName", txtLastName.Text); 

如果你的字段名稱已嵌入空格,不同的數據庫 不同,有些需要單一反引號(關鍵左1)在場地周圍。如'名字'。有些使用方括號, 如[名字]。