VB 2010 error (INSERT INTO) syntax error [duplicate]

夙愿已清 提交于 2019-12-13 09:57:21

问题


I have a program in VB.NET that will input data from textboxes into an Access database. Here is sample image:

This is the code I am using and it gives me an error:

m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users1 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()

回答1:


The reason your SQL is failing is that "add" is a reserved word. i.e. you cannot use it without putting it in square brackets - [add]. As above you should parameterise your query, so one of these will work...

Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) values (@num,@name1,@pass,@add,@phone)", con)
    oleCmd.Parameters.Add("@num", OleDbType.Integer).Value = Textbox1.Text
    oleCmd.Parameters.Add("@name1", OleDbType.VarChar).Value = Textbox2.Text
    oleCmd.Parameters.Add("@pass", OleDbType.VarChar).Value = Textbox3.Text
    oleCmd.Parameters.Add("@address", OleDbType.VarChar).Value = Textbox4.Text
    oleCmd.Parameters.Add("@phone", OleDbType.Integer).Value = Textbox5.Text
    oleCmd.ExecuteNonQuery()
End Using

Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) Values (?,?,?,?,?)", con)
    oleCmd.Parameters.AddWithValue("?", Textbox1.Text)
    oleCmd.Parameters.AddWithValue("?", Textbox2.Text)
    oleCmd.Parameters.AddWithValue("?", Textbox3.Text)
    oleCmd.Parameters.AddWithValue("?", Textbox4.Text)
    oleCmd.Parameters.AddWithValue("?", Textbox5.Text)
    oleCmd.ExecuteNonQuery()
End Using

Note, it will fail if the data types do not match what you are trying to insert, so if you try to insert text in num or phone it will fail. You will need to validate your input and preferably convert them rather than use the textbox Text.



来源:https://stackoverflow.com/questions/41259352/vb-2010-error-insert-into-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!