在数据库中插入数据

时间:2014-02-06 16:01:09

标签: vb.net

我有这个代码但是当我尝试执行它时,我总是会得到一个消息框,上面写着Syntax error in INSERT statement我不知道什么是错的。有人能帮我吗?我是新手

 Private Sub Button1_Click(ByVal sender As System.Object, 
            ByVal e As System.EventArgs) Handles Button1.Click

        If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Then
            MsgBox("some fields are empty ")
            Exit Sub
        ElseIf TextBox2.Text <> TextBox3.Text Then
            MsgBox("password do not match ")
            Exit Sub
        Else
            ans = MsgBox(" are you want to ADD this user? ", MsgBoxStyle.YesNo,
                   "confirm ")
            If ans = MsgBoxResult.Yes Then
                Try
                    Dim SqlQuery = "INSERT INTO login (user,pass) VALUES _ 
                      ('" & TextBox1.Text & "','" & TextBox2.Text & "')"
                    Dim sqlcommand As New OleDbCommand
                    With sqlcommand
                        .CommandText = SqlQuery
                        .Connection = conn
                        .ExecuteNonQuery()
                    End With
                    MsgBox("User Succesfully added", MsgBoxStyle.Information)
                    TextBox1.Text = ""
                    TextBox2.Text = ""
                    TextBox3.Text = ""

                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Else
                Exit Sub
            End If

        End If

    End Sub

2 个答案:

答案 0 :(得分:5)

假设您正在使用MS-Access,USER这个词是保留关键字,您需要将其封装在方括号中

但是让我们尝试使用参数化查询来解决sql注入和密码或用户名中单引号的问题

Dim SqlQuery = "INSERT INTO login ([user],pass) VALUES (?,?)"
Dim sqlcommand As New OleDbCommand
With sqlcommand
    .CommandText = SqlQuery
    .Connection = conn
    .Parameters.AddWithValue("@p1",TextBox1.Text)
    .Parameters.AddWithValue("@p2",TextBox2.Text)
    .ExecuteNonQuery()
End With

?占位符将替换为命令的Parameters集合中定义的参数的实际值。使用OleDb时,参数不会被其名称(因此是匿名占位符)识别,而是按其位置识别。这意味着集合中的第一个参数替换了第一个占位符,依此类推....顺便说一下,框架知道如何准备属性字符串参数(或日期或小数)的值,将相应的引号或小数分隔符放在值

答案 1 :(得分:2)

除了您面临的其他问题(查找参数化查询)之外,您还错误地连接了字符串。

更改

Dim SqlQuery = "INSERT INTO login (user,pass) VALUES _ 
                  ('" & TextBox1.Text & "','" & TextBox2.Text & "')"

要:

Dim SqlQuery = "INSERT INTO login (user,pass) VALUES " & _ 
                  "('" & TextBox1.Text & "','" & TextBox2.Text & "')"