Interacting with Databases Using ASP.NET 2.0 with the Microsoft Data Access Application Block - Executing a DML statement using the Data Access Application Block
(Page 5 of 6 )
In all of the previous sections, we only retrieved information from a SQL Server database using the Data Access Application Block. Now, we shall work on executing any DML statement using the Data Access Application Block.
The following is the complete code needed to execute any DML statement using the Data Access Application Block.
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Try
Me.lblMsg.Text = SQLExecute("delete from
HumanResources.department") & " rows deleted"
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
Private Function SQLExecute(ByVal SQL As String) As String
Dim RowsAffected As Integer
Try
Dim db As SqlDatabase = DirectCast
(DatabaseFactory.CreateDatabase("AdventureWorks"), SqlDatabase)
RowsAffected = db.ExecuteNonQuery(CommandType.Text,
SQL)
Return RowsAffected
Catch ex As Exception
Throw New Exception("Unable to execute DML:" &
ex.Message)
End Try
End Function
EndClass
In the above code, you can understand that I am executing a DML statement using the “ExecuteNonQuery” method available in the class “SqlDatabase.” As we are executing only DML and not any stored procedure, we need to specify that the “CommandType” is “Text.” The “ExecuteNonQuery” also returns the number of rows affected, once a DML command is executed. The same is being returned from the “SQLExecute” method.
Next: Summary >>
More ASP.NET Articles
More By Jagadish Chaterjee