需要一点帮助。
我目前正在使用此代码将项目添加到Visual Basic 2010中的Access数据库
Imports System
Imports System.Data
Imports System.Collections
Imports System.Windows.Forms
Imports System.Resources
Imports System.Data.OleDb
Public Class Form2
Dim myConnection = New System.Data.OleDb.OleDbConnection()
Dim SqlCommand As OleDb.OleDbCommand = New OleDb.OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'connects to the database when the form loads
myConnection = New System.Data.OleDb.OleDbConnection()
myConnection.ConnectionString = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source =project.accdb; Persist Security Info =False;"
Try
myConnection.Open()
Catch ex As Exception
MsgBox("Error Please Go Back And Try Again")
Console.WriteLine(ex.Message)
End Try
'adds items to the dropdown menu
Dim result As OleDb.OleDbDataReader
Dim sqlText As String
Dim add1 As Integer = 0
If myConnection.State <> ConnectionState.Open Then
MsgBox("Connection is not open")
Exit Sub
End If
sqlText = "select * from groups"
SqlCommand = New OleDbCommand(sqlText, myConnection)
result = SqlCommand.ExecuteReader()
Do While result.Read()
ComboBox1.Items.Insert(add1, result.GetValue(0))
add1 = add1 + 1
Loop
result = Nothing
SqlCommand = Nothing
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Insert button
Dim item As String = ""
Dim price As String = ""
Dim group As String = ""
Dim dateandtime As Double
Dim dateandtime2 As String = ""
Dim sqlInsert As String = ""
Dim result As Integer = -1
Dim SqlCommand As OleDb.OleDbCommand = New OleDb.OleDbCommand
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Item and Price Required!")
Exit Sub
End If
item = TextBox1.Text
price = TextBox2.Text.Trim
group = ComboBox1.Text.Trim
dateandtime = DateTimePicker1.Value.ToOADate()
dateandtime2 = dateandtime.ToString
sqlInsert = "INSERT INTO purchases (item, price, groupName, datetime) VALUES ('" + item + "', '" + price + "', '" + group + "', '" + dateandtime2 + "')"
Try
SqlCommand.Connection = myConnection
SqlCommand.CommandText = sqlInsert
result = SqlCommand.ExecuteNonQuery()
If result = 0 Then
MsgBox("No records inserted!")
Else
MsgBox(CStr(result) & " record inserted!")
End If
TextBox1.Clear()
TextBox2.Clear()
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
result = -1
SqlCommand = Nothing
End Sub
但每次尝试添加任何内容时,我都会收到此异常 在此处查看:http://i.stack.imgur.com/itd39.jpg 有什么想法吗?
答案 0 :(得分:1)
MystPhysX,
我意识到这个答案对于你的问题来说已经晚了几年,但对于那些在网上搜索类似问题的人来说(这就是我发现这个问题的方式),我想提供解决方案对我的问题有用。
您正在使用&#34; +&#34;运算符以连接Visual Basic中的sqlInsert字符串。我相信使用&#34;&amp;&#34;运算符将解决抛出的错误。以下链接将提供更多信息。
http://msdn.microsoft.com/en-us/library/te2585xw.aspx
以下是经过编辑的代码行:
sqlInsert = "INSERT INTO purchases (item, price, groupName, datetime) VALUES ('" & item & "', '" & price & "', '" & group & "', '" & dateandtime2 & "')"