插入语句中的语法错误

时间:2013-02-26 11:33:55

标签: vb.net oledb

我是数据库连接的新手,当我遇到cmdInsert.ExecuteNonQuery()行的问题时,它说INSERT INTO语句有语法错误,我无法弄清楚问题所在:< / p>

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

3 个答案:

答案 0 :(得分:1)

我强烈建议不要通过将字符串连接在一起来构建SQL字符串的例程。您对SQL-Injection完全敞开大门,特别是如果这是基于Web的。您应该在字符串中使用占位符参数构建命令,然后将参数添加到命令对象。按照命令中显示的顺序添加参数...例如

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

如果您的字段名称包含嵌入空格,则可以使用不同的数据库   不同的是,有些需要单个反引号(数字左侧的键)   1)围绕场地。比如'名字'。有些人使用方括号,   例如[名字]。

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

警告:Bobby正在关注你。

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