从 vb.net 将值插入 Access db
Posted
技术标签:
【中文标题】从 vb.net 将值插入 Access db【英文标题】:Insert values into Access db from vb.net 【发布时间】:2014-07-09 01:03:31 【问题描述】:尝试将值插入访问数据库时出现错误。错误说:
System.Data.dll 中出现“System.Data.OleDb.OleDbException”类型的未处理异常。附加信息:INSERT INTO 语句中的语法错误。
所有值类型都是我的 Access db 中的文本。
这是我的代码:
谢谢。
Public Class NewUser
Dim cnn2 As New OleDb.OleDbConnection
Private Sub NewUser_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cnn2 = New OleDb.OleDbConnection
cnn2.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Chris\Desktop\UserInfo.accdb"
frmMain.Visible = True
Me.Visible = False
End Sub
Private Sub RefreshData()
If Not cnn2.State = ConnectionState.Open Then
cnn2.Open()
End If
End Sub
Private Sub btnCreate_Click(sender As System.Object, e As System.EventArgs) Handles btnCreate.Click
If (txtPassword.Text = txtConfirm.Text) Then
greenP.Visible = True
Dim cmd2 As New OleDb.OleDbCommand
If Not cnn2.State = ConnectionState.Open Then
cnn2.Open()
End If
cmd2.Connection = cnn2
cmd2.CommandText = "INSERT INTO Users (FirstName, LastName, Address, City, State, Zip, Email, Username, Password) VALUES ('" & txtFirst.Text & "', '" & txtLast.Text & "', '" & txtAddress.Text & "', '" & txtCity.Text & "', '" & txtState.Text & "', '" & txtZip.Text & "', '" & txtEmail.Text & "', '" & txtUsername.Text & "', '" & txtPassword.Text & "')"
cmd2.ExecuteNonQuery()
cnn2.Close()
txtAddress.Clear()
txtCity.Clear()
txtConfirm.Clear()
txtEmail.Clear()
txtFirst.Clear()
txtLast.Clear()
txtPassword.Clear()
txtState.Clear()
txtUsername.Clear()
txtZip.Clear()
txtFirst.Focus()
Else
redP.Visible = True
MessageBox.Show("Passwords do not match. Please enter again", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtConfirm.Clear()
txtConfirm.Focus()
End If
End Sub
结束类
【问题讨论】:
【参考方案1】:cmd2.CommandText = "INSERT INTO Users (FirstName, LastName, Address, City, [State], Zip, Email, Username, [Password]) VALUES ('" & txtFirst.Text & "', '" & txtLast.Text & "', '" & txtAddress.Text & "', '" & txtCity.Text & "', '" & txtState.Text & "', '" & txtZip.Text & "', '" & txtEmail.Text & "', '" & txtUsername.Text & "', '" & txtPassword.Text & "')"
现在试试这个,那些用于表名的 MS Access 关键字正在被封装。 [tablename] 相当于其他 RDBMS 上的反引号。它用作表名的转义关键字。
【讨论】:
以上是关于从 vb.net 将值插入 Access db的主要内容,如果未能解决你的问题,请参考以下文章
在使用 VB.NET 的 Access 中将空字符串字段插入为 null