2014-04-29 160 views
1

我有3個文本框用作聯繫表單。我正嘗試使用VB來獲取這些數據並將其添加到我的數據庫中。 我已經運行調試,它說錯誤在INSERT INTO字符串中。 ![調試屏幕抓取] [1]:http://i.stack.imgur.com/ufYPs.png使用VB.Net將文本從文本框插入到Access 2010數據庫中

任何想法?

Imports System 

進口System.Data 進口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

USER是在MS-訪問保留關鍵字,要使用它作爲一個表名你的需要把它們放在方括號

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 
+0

感謝您的答覆。 – mredfern79

+0

感謝您的回覆,我已經嘗試過2件事。如果我添加Using語句,最終會出現構建錯誤,說明'dbconn'和'objcmd'隱藏了變量並封閉了塊。 – mredfern79

+0

我試過運行沒有'使用語句',只是添加方括號給用戶'[用戶]'。在調試以下錯誤在HTTP拋出異常_Unhandled在行940,列13://本地主機:1169 /的ScriptResource.axd d = DT3YJR8QaqV61-teuz0hgq5a3FQA8MHrkniUz6btQKrdAAJIBru1i4ufsCj0lnk7SbkE-BpmROGP1Po5qv6t2Vic05otOdeKe1XYXd0-lSx5dnzvvNHmrEh9dnlkqayZF065umFxuLGoU_dhd8lCxQ2&T = ffffffffda74082d 0x800a139e - JavaScript的運行時錯誤:?Sys.WebForms .PageRequestManagerParserErrorException:無法解析從服務器收到的消息._ – mredfern79

相關問題