0

我是 VB.net 的新用户(2 周)并且来自 php 背景,我发现这很难。我创建了一个小表单,应该将一些数据插入到访问 mdb 数据库中。但是,我不断收到以下错误:

System.Data.OleDb.OleDbException

我在粘贴的代码中概述了发生此错误的位置,如果有人能指出我哪里出错了,我将不胜感激。非常感谢。

Imports System.Data.OleDb

Public Class frmMain

    Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\domain\storage1.mdb"

    Dim cnnOLEDB As New OleDbConnection(strConnectionString)
    Dim cmdOLEDB As New OleDbCommand
    Dim cmdInsert As New OleDbCommand
    Dim cmdUpdate As New OleDbCommand
    Dim cmdDelete As New OleDbCommand
    Dim cmd As OleDbCommand

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

    End Sub


    Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
        Dim first, last As String
        Dim age As Integer

        first = txtFirstName.Text
        last = txtLastName.Text
        age = txtAge.Text

        Dim InsertQuery As String

        InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"

        cnnOLEDB.Open()
        Dim cmd As OleDbCommand = New OleDbCommand(InsertQuery, cnnOLEDB)
        cmd.Parameters.AddWithValue("first", txtFirstName.Text)
        cmd.Parameters.AddWithValue("last", txtLastName.Text)
        cmd.Parameters.AddWithValue("age", txtAge.Text)


        cmd.ExecuteNonQuery() <--- ERROR
        cnnOLEDB.Close()
        MessageBox.Show("Insert complete.")
    End Sub
End Class
4

2 回答 2

1

First并且Last是 Jet 4.0 的保留字。它们不应用作列名。Access 本身会让你侥幸逃脱,SQL 代码就不那么宽容了。如果您无法避免使用这些词,请[first]在解决它们时尝试将它们放在方括号中。有关保留字的更多信息,请参阅http://support.microsoft.com/kb/248738

于 2013-10-18T09:30:18.203 回答
1

问题在这里:

InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"

cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)

尝试这个:

InsertQuery = "INSERT INTO Details (first,last,age) VALUES (@first, @last, @age)"

然后对于参数:

cmd.Parameters.AddWithValue("@first", txtFirstName.Text)
cmd.Parameters.AddWithValue("@last", txtLastName.Text)
cmd.Parameters.AddWithValue("@age", txtAge.Text)

然后,您可以删除这些行,因为您不需要它们:

Dim first, last As String
Dim age As Integer

first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
于 2013-10-18T09:15:20.593 回答