Connecting to Different Databases Using ASP.NET 2.0 - Connecting to Microsoft SQL Server database using the GenericDatabase class
(Page 4 of 5 )
The previous sections concentrated on database and SqlDatabase classes to connect and work with Microsoft SQL Server. In this section, I shall introduce you to connecting to Microsoft SQL Server database using the GenericDatabase class.
The following code uses the GenericDatabase class to connect to a Microsoft SQL Server database.
ImportsSystem.Data
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
Dim db As New GenericDatabase
(ConfigurationManager.ConnectionStrings
("AdventureWorks").ConnectionString,
System.Data.SqlClient.SqlClientFactory.Instance)
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 is not much difference between the code in the previous sections and this section, except that I used the GenericDatabase class available in the “Microsoft.Practices.EnterpriseLibrary.Data” namespace. You can also observe that I am using “ConfigurationManager” to retrieve connection string from the “web.config” file.
Connecting to OLEDB data sources using the GenericDatabase class
The previous section concentrated on using the GenericDatabase class to connect and work with Microsoft SQL Server. In this section, I shall continue with the same class and work with OLEDB data sources.
Before you begin, modify your web.config as follows:
<configuration>
<appSettings/>
<connectionStrings>
<!--<add name="AdventureWorks"
connectionString="Database=AdventureWorks;Server=(local)
SQL2k5;Integrated Security=SSPI;"
providerName="System.Data.SqlClient"/> -->
<add name="AdventureWorks" connectionString="Provider=
sqloledb;Data Source=.sql2k5;Initial
Catalog=AdventureWorks;Integrated Security=SSPI;"/>
</connectionStrings>
The following code uses the GenericDatabase class to connect to Microsoft SQL Server database using an OLEDB connection string.
ImportsSystem.Data
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
Dim db As New GenericDatabase
(ConfigurationManager.ConnectionStrings
("AdventureWorks").ConnectionString,
System.Data.OleDb.OleDbFactory.Instance)
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 an Oracle database using the GenericDatabase class >>
More ASP.NET Articles
More By Jagadish Chaterjee