The Provider Factory in ADO.NET 2.0 - Creating Provider Independent Data Access
(Page 4 of 4 )
The DbProviderFactory object gives you an indication of how you may use it for the purposes of writing a generic data access program, which may be connected to the provider of your choice at run time, as shown in the next picture.

As the code in the next paragraph shows, once you get an instance of the DbProviderFactory, you can create a connection using the CreateConnection() method. Similarly you can create the DbDataAdapter using the CreateDataAdapter method; DbParameter using CreateParameter(); and DbDataCommand using CreateCommand(). All this can be set at run time passing the strings Provider, ConnectionString, and CommandText.
The following code does not show all this; it shows the connection being opened with a connection string taking strings from textboxes and using the factory model (the CreateConnection() function is highlighted in the code).
Imports System.Data
Imports System.Data.Common
Partial Class Generic
Inherits System.Web.UI.Page
Private connstrg As String
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dstrg As System.Data.Common.DbProviderFactory
dstrg = Data.Common.DbProviderFactories.GetFactory(TextBox1.Text)
Dim conn As Data.Common.DbConnection = dstrg.CreateConnection()
conn.ConnectionString = TextBox2.Text
conn.Open()
Response.Write("open")
conn.Close()
End Sub
End Class
When the button is clicked the above code runs and you will see the following display. As long as you insert proper values into textbox1 and textbox2 which are compatible, the connection opens. In the example shown the boxes are hard coded, but it is possible to have drop-downs from which you may make connections to anticipated data sources. In fact the whole process of data retrieval can now be written in a generic format since all objects are derived from the DbProviderFactory instance. If you need to connect to the other providers look up the table of providers shown earlier.
Summary
The Provider Factory Model will be useful for writing provider independent data access code. It must be realized that the ConnectionString as required by this model should not contain the keyword "Provider" (see textbox2's text). The password has been masked in the image but it was in clear text.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |