简体   繁体   English

使用VB.Net将文本从文本框中插入并访问Access 2010数据库

[英]Insert text from a text box into and Access 2010 DataBase using VB.Net

I have 3 text boxes I am using as a contact form. 我有3个文本框用作联系表格。 I am trying to use VB to take this data and add it into my database. 我正在尝试使用VB来获取这些数据并将其添加到我的数据库中。 I have run debugging and it says the error is in the INSERT INTO string. 我已经运行调试,它说错误在INSERT INTO字符串中。 ![Screen Grab of Debugging] [1]: http://i.stack.imgur.com/ufYPs.png ![调试画面抓取] [1]: http//i.stack.imgur.com/ufYPs.png

Any ideas? 有任何想法吗?

Imports System

Imports System.Data Imports System.Data.OleDb Partial Class Contact Inherits System.Web.UI.Page 导入System.Data导入System.Data.OleDb局部类Contact继承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

USER is a reserved keyword in MS-Access, To use it as a table name your need to enclose it in square brackets USER是MS-Access中的保留关键字,要将其用作表名,需要将其括在方括号中

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

As a side note, try to use the Using Statement when you work with disposable objects. 附带说明,在处理一次性对象时,请尝试使用Using语句

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM