VB 2010错误(INSERT INTO)语法错误

时间:2016-12-21 09:32:53

标签: vb.net vb.net-2010

我在VB.NET中有一个程序,它将文本框中的数据输入到Access数据库中。这是样本图片:

enter image description here

这是我正在使用的代码,它给了我一个错误:

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 个答案:

答案 0 :(得分:1)

SQL失败的原因是“add”是一个保留字。即,如果不将其放在方括号中,就不能使用它 - [添加]。如上所述,您应该参数化您的查询,因此其中一个将起作用...

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

注意,如果数据类型与您要插入的内容不匹配,则会失败,因此如果您尝试在num或phone中插入文本,则会失败。您需要验证输入并最好转换它们,而不是使用文本框文本。