VB.Net - 使用OleDb将数据插入Access数据库

时间:2016-03-02 22:09:37

标签: vb.net ms-access oledb

您能否告诉我我使用的代码有什么问题?每次执行此操作时,都会抛出异常(无法连接到数据库)

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

Dim conn As New System.Data.OleDb.OleDbConnection()

conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb"

Dim sql As String = String.Format("INSERT INTO login     VALUES('{username}','{password}','{secques}','{secans}')", txt_username.Text, txt_passwd.Text, txt_secquestion.Text, txt_secansw.Text)

            Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

            'Open Database Connection
            sqlCom.Connection = conn
            conn.Open()
            Dim icount As Integer = sqlCom.ExecuteNonQuery
            MessageBox.Show(icount)
            MessageBox.Show("Successfully registered..", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error)

        Catch ex As Exception
            MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        cmd_submit2_Click(sender, e)

    End If
End Sub

我正在使用Access 2013和VS 2015社区,如果有帮助的话。谢谢。

1 个答案:

答案 0 :(得分:1)

您应该对命令使用参数化方法。 参数化查询消除了Sql Injection的可能性,如果字符串值格式不正确,则不会出错。

请注意,如果您未在异常块中执行任何操作,则最好将其删除并让异常显示或至少显示Exception.Message值,以便您了解实际错误。

最后,应使用Using语句创建每个一次性对象,以确保正确关闭并处理此类对象(特别是OleDbConnection)

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

    Dim sql As String = "INSERT INTO login VALUES(@name, @pass, @sec, @sw)"
    Using conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb")
    Using sqlCom = New System.Data.OleDb.OleDbCommand(sql, conn)
         conn.Open()
         sqlCom.Parameters.Add("@name", OleDbType.VarWChar).Value = txt_username.Text
         sqlCom.Parameters.Add("@pass", OleDbType.VarWChar).Value = txt_passwd.Text
         sqlCom.Parameters.Add("@sec", OleDbType.VarWChar).Value = txt_secquestion.Text
         sqlCom.Parameters.Add("@sw", OleDbType.VarWChar).Value =  txt_secansw.Text 
         Dim icount As Integer = sqlCom.ExecuteNonQuery
    End Using
    End Using
End Sub

请记住,省略INSERT INTO语句中的字段名称要求您为登录表中的每个字段以及表所需的确切顺序提供值(因此最好插入字段名称)< / p>

例如,如果您的表只有4个已知字段:

Dim sql As String = "INSERT INTO login (username, userpass, secfield, secfieldsw) " & _ 
                    "VALUES(@name, @pass, @sec, @sw)"