使用VB.Net将文本框中的文本插入Access 2010 DataBase

时间:2014-04-29 21:21:20

标签: database ms-access-2010 vb.net-2010

我使用了3个文本框作为联系表单。我正在尝试使用VB获取此数据并将其添加到我的数据库中。 我已经运行调试,它说错误在INSERT INTO字符串中。 ![调试屏幕抓取] [1]:http://i.stack.imgur.com/ufYPs.png

有什么想法吗?

Imports System

导入System.Data Imports System.Data.OleDb 部分班级联系     继承System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Name As String = txtName.Text
    Dim Email As String = tbxEmail.Text
    Dim Comment As String = tbxComment.Text

    Dim objConnection As OleDbConnection = Nothing
    Dim objcmd As OleDbCommand = Nothing

    Dim strSql As String
    Dim dbConn As OleDbConnection = Nothing

    dbConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Z:\Documents\Databases\user.accdb")
    dbConn.Open()

    strSql = "INSERT INTO user (username, email, comments) VALUES (?,?,?)"
    objcmd = New OleDbCommand(strSql, dbConn)
    objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@username", Name))
    objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@email", Email))
    objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@comments", Comment))
    objcmd.ExecuteNonQuery()


    dbConn.Close()
    Response.Write("Submitted Successfully")

End Sub

1 个答案:

答案 0 :(得分:1)

USER是MS-Access中的保留关键字,要将其用作表名,需要将其括在方括号中

strSql = "INSERT INTO [user] (username, email, comments) VALUES (?,?,?)"

作为旁注,请在使用一次性物品时尝试使用Using Statement

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Name As String = txtName.Text
    Dim Email As String = tbxEmail.Text
    Dim Comment As String = tbxComment.Text

    Using dbConn = New OleDbConnection(".......")
        dbConn.Open()
        Dim strSql = "INSERT INTO [user] (username, email, comments) VALUES (?,?,?)"
        Using objcmd = New OleDbCommand(strSql, dbConn)
            objcmd.Parameters.AddWithValue("@username", Name)
            objcmd.Parameters.AddWithValue("@email", Email)
            objcmd.Parameters.AddWithValue("@comments", Comment)
            objcmd.ExecuteNonQuery()
        End Using
    End Using
    Response.Write("Submitted Successfully")
End Sub