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
4

3 回答 3

1

我强烈建议不要通过将字符串连接在一起来构建 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 的左侧键)。比如“名字”。有些使用方括号,例如 [first name]。

于 2013-03-20T03:11:28.390 回答
0

尝试这个

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

于 2013-02-26T11:45:24.297 回答
0

警告:鲍比在看着你。

cmdInsert.CommandText = _
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"
于 2013-02-26T11:45:58.633 回答