Connecting to Different Databases Using ASP.NET 2.0 - Connecting to Microsoft SQL Server database using the SqlDatabase class
(Page 3 of 5 )
The previous two sections concentrated on the database class to connect and work with Microsoft SQL Server. In this section, I shall introduce you to connecting to a Microsoft SQL Server database using the SqlDatabase class.
The following code uses the SqlDatabase class to connect to a Microsoft SQL Server database.
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Dim db As New SqlDatabase
(ConfigurationManager.ConnectionStrings
("AdventureWorks").ConnectionString)
Me.lblMsg.Text = db.ConnectionStringWithoutCredentials
Dim dt As DataTable = db.ExecuteDataSet(CommandType.Text,
"select * from HumanResources.department").Tables(0)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub
EndClass
There exists not much difference between the code in the previous section and this section, except that I used the SqlDatabase class available in the “Microsoft.Practices.EnterpriseLibrary.Data.Sql” namespace. You can also observe that I am using “ConfigurationManager” to retrieve connection string from the “web.config” file.
If you wanted to use the DatabaseFactory class to instantiate a SqlDatabase object, you can do it as follows:
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Dim db As SqlDatabase = DirectCast
(DatabaseFactory.CreateDatabase("AdventureWorks"), SqlDatabase)
Me.lblMsg.Text = db.ConnectionStringWithoutCredentials
Dim dt As DataTable = db.ExecuteDataSet(CommandType.Text,
"select * from HumanResources.department").Tables(0)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub
EndClass
Next: Connecting to Microsoft SQL Server database using the GenericDatabase class >>
More ASP.NET Articles
More By Jagadish Chaterjee