这是我在我的提交按钮后面的代码,我有两个文本框名称和电子邮件,我想要添加到我的数据库中,如果有人可以提供帮助,那就无法理解
Dim Strnm As String = Request.Form("txtname")
Dim Strem As String = Request.Form("txtemail")
Dim objConnection As OleDbConnection = Nothing
Dim objcmd As OleDbCommand = Nothing
Dim StrSQL As String
Dim dbConn As OleDbConnection = Nothing
Dim filepath = "G:\WebSites\WebSite1\App_Data\register_log.ldf"
dbConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\registration.accdb")
dbConn.Open()
StrSQL = "insert into tblregistration (Name, E-mail) values (?,?)"
objcmd = New OleDbCommand(StrSQL, dbConn)
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@txtname", Strnm))
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@txtemail", Strem))
'close connection
dbConn.Close()
Response.Write("submitted successfully")
答案 0 :(得分:0)
您没有执行查询。您的代码也可以使用Using
块来缩短,这些块声明和处理事物:
Dim Strnm As String = Request.Form("txtname")
Dim Strem As String = Request.Form("txtemail")
Dim StrSQL = "insert into tblregistration (Name, E-mail) values (?,?)"
Using dbConn = New OleDbConnection(connection string...),
objcmd = New OleDbCommand(StrSql, objConnection)
dbConn.Open()
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@txtname", Strnm))
objcmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@txtemail", Strem))
objcmd.ExecuteNonQuery ' execute the query
End Using ' close and dispose of dbConn, objcmd
Response.Write("submitted successfully")
代码中还声明了2个Connection对象(objConnection
和dbConn
)。
Using
就像Dim
一样,到目前为止代码可以在一行代码中声明和初始化。但主要是它确保这些东西在街区尽头关闭并处理掉。该代码还使用构造函数在创建时将SQL和Connection传递给dbConn
和objCmd
。它只保存了一两行代码,但假设它们从创建时就具有所需的内容。
您还可以使用函数来返回Connection
对象,这样您就不必在整个代码中都有连接字符串。请参阅this answer。