我尝试使用VB将数据插入MSaccess数据库,但在完成代码时遇到一些问题
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'BD Connection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Peter\Documents\Database1.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Private Sub FindButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindButton.Click
'Query BD
myConnection.Open()
DescriptionText.Clear()
CostText.Clear()
PriceText.Clear()
Dim str As String
str = "SELECT * FROM Table1 WHERE (Code = '" & CodeText.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
DescriptionText.Text = dr("Description").ToString
CostText.Text = dr("Cost").ToString
PriceText.Text = dr("Price").ToString
End While
myConnection.Close()
End Sub
Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
'Insert BD
Dim str As String
myConnection.Open()
CodeText.Clear()
DescriptionText.Clear()
CostText.Clear()
PriceText.Clear()
str = "INSERT INTO Table1 (Code, Description, Cost, Price) Values (CodeText.Text, DescriptionText.Text, CostText.Text, PriceText.Text) VALUES ('CodeText.Text', 'DescriptionText.Text', 'CostText.Text', 'PriceText.Text')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
MsgBox("saved")
myConnection.Close()
End Sub
End Class
我的查询子工作正常,但是当我尝试插入数据时,它在" cmd.ExecuteNonQuery()"上给我一个错误。
你能帮我找错吗?
答案 0 :(得分:3)
您的INSERT
查询语法不正确。您不能简单地将Textbox.Text
作为字符串添加到值中。你必须逃脱它们。
但我强烈建议对SELECT
和INSERT
语句使用参数化查询:
Dim insert As String = "INSERT INTO Table1 (Code, Description, Cost, Price) Values (?, ?, ?, ?)"
Dim insertCmd As New OleDbCommand(insert, myConnection)
insertCmd.Parameters.Add(New OleDbParameter("Code", CodeText.Text))
insertCmd.Parameters.Add(New OleDbParameter("Description", DescriptionText.Text))
insertCmd.Parameters.Add(New OleDbParameter("Cost", Double.Parse(CostText.Text)))
insertCmd.Parameters.Add(New OleDbParameter("Price", Double.Parse(PriceText.Text)))
insertCmd.ExecuteNonQuery()
我假设您的Cost
和Price
数据库字段是数字字段,因此我使用Double.Parse
进行转换。 Code
似乎是一个文本字段,因此无需转换。如果我的建议类型不正确,您必须对此进行调整,有Integer.Parse
,Decimal.Parse
等。
最后,此处SELECT
部分进行了优化:
Dim qry As String = "SELECT * FROM Table1 WHERE (Code = ?)"
Dim selectCmd As OleDbCommand = New OleDbCommand(qry, myConnection)
selectCmd.Parameters.Add(New OleDbParameter("Code", CodeText.Text))
selectCmd.ExecuteNonQuery()
答案 1 :(得分:0)
试试这个
str = "INSERT INTO Table1 (Code, Description, Cost, Price) Values ('" + CodeText.Text + "', '" + DescriptionText.Text + "', '" + CostText.Text + "', '" + PriceText.Text + "')"