需要一些幫助。使用Visual Basic 2010中的SQL將項添加到Access數據庫
我目前使用此代碼在Visual Basic 2010
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
項目添加到Access數據庫但每次我嘗試添加任何東西在這裏查看 時間我得到這個異常:http://i.stack.imgur.com/itd39.jpg 有什麼想法?
看一看爲的SQLInsert的價值,並檢查它是否有效的SQL語法 – sasfrog
謝謝回答!我看了一下這個鏈接http://www.w3schools.com/sql/sql_insert.asp,語法看起來正確。我唯一缺少的是我無法指定的行號,因爲我將來需要編程以繼續添加行,但這個具有不同變量的代碼以另一種形式工作,所以我不知道爲什麼它不是沒有工作。 – MystPhysX
你知道如何使用sql profiler嗎?如果在運行插入時可以運行軌跡,則可能會發現問題所在。我的賭注是,你的字符串concatination在某種程度上基於插入的值剝落,例如.... VALUES('d'adario',..... –