我是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
答案 0 :(得分: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
答案 1 :(得分:1)
First
和Last
是Jet 4.0的保留字。它们不应用作列名。访问本身将让你逃脱它,SQL代码有点不太宽容。如果你无法避免使用这些词,请在解决它们时尝试将它们放在方括号[first]
中。有关保留字的更多信息,请参阅http://support.microsoft.com/kb/248738。