当我运行下面的代码时,我不断收到错误消息:Syntax error (missing operator) in query expression
。我做错了什么?
con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb"
connOledb.ConnectionString = con
connOledb.Open()
command = New OleDb.OleDbCommand("INSERT INTO Artikels VALUES('1'," + txtOmsch.Text + _
"','" + txtCat.Text + "','" + txtAPE.Text + _
"','" + txtMarge.Text + "','" + txtVPE.Text + _
"','" + txtEen.Text + "','" + txtLen.Text + _
"','" + txtBreed.Text + "','" + txtDiep.Text + _
txtOmsch.Text + "');")
command.Connection = connOledb
command.ExecuteNonQuery()
答案 0 :(得分:2)
您错过了第二个值的单引号。试试这个,
command = New OleDb.OleDbCommand("INSERT INTO Artikels VALUES('1','" + txtOmsch.Text + _
"','" + txtCat.Text + "','" + txtAPE.Text + _
"','" + txtMarge.Text + "','" + txtVPE.Text + _
"','" + txtEen.Text + "','" + txtLen.Text + _
"','" + txtBreed.Text + "','" + txtDiep.Text + _
txtOmsch.Text + "');")
您的代码在使用sql注入时容易受到攻击,请使用参数化查询,因为您使用的是ADO.NET
,请更好地尝试以下代码,
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb"
Dim query As String = "INSERT INTO Artikels VALUES(@val1, @Omsch, @Cat, @Ape, @VPE, @Een, @len, @breed, @diep,@Omsch)")
Using connOledb As New OleDbConnection(con)
Using command As New OleDbCommand()
With command
.Connection = con
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@val1",1)
.Parameters.AddWithValue("@Omsch",txtOmsch.Text)
.Parameters.AddWithValue("@Cat",txtCat.Text)
.Parameters.AddWithValue("@Ape",txtAPE.Text)
.Parameters.AddWithValue("@VPE",txtVPE.Text)
.Parameters.AddWithValue("@Een",txtEen.Text )
.Parameters.AddWithValue("@len",txtLen.Text)
.Parameters.AddWithValue("@breed",txtBreed.Text)
.Parameters.AddWithValue("@diep",txtDiep.Text)
End with
Try
connOledb.Open()
command.ExecuteNonQuery()
Catch(ex as OleDBException)
Msgbox(ex.Message.Tostring())
End Try
End Using
End Using
或Add
.Add("@Omsch", OleDbType.VarChar, 30).Value = txtOmsch.Text
答案 1 :(得分:0)
缺少第二列的第一列
con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb"
connOledb.ConnectionString = con
connOledb.Open()
command = New OleDb.OleDbCommand("INSERT INTO Artikels VALUES('1','" + txtOmsch.Text + _
"','" + txtCat.Text + "','" + txtAPE.Text + _
"','" + txtMarge.Text + "','" + txtVPE.Text + _
"','" + txtEen.Text + "','" + txtLen.Text + _
"','" + txtBreed.Text + "','" + txtDiep.Text + _
txtOmsch.Text + "');")
command.Connection = connOledb
command.ExecuteNonQuery()