Morning to see a brother's article, very hard to implement the code only to change the configuration to access different types of databases, their own to implement the factory model. The spirit is commendable, but no one knows that C # has made a factory of its own access to different types of databases. Here I put the use of the factory example posted out for the brothers do not know the reference, the experts can be ignored.
First is the configuration file: The providername is the different database type specified
<connectionStrings>
<add name="..." connectionString=" ..." providerName="System.Data.OleDb" />
<add name="..." connectionString=" ..." providerName="System.Data.SqlClient" />
</connectionStrings>
Here's a look at this class that uses the factory:
Class DATABASEFAC
{
Private DbConnection cnn;//Abstract type
Private DbCommand cmd;//Abstract type
Private DbProviderFactory provider;
Public Databasefac ()
{
To remove a string that identifies a database type from a configuration file
String providername = Configurationmanager.connectionstrings[1]. ProviderName;
Create a corresponding instance based on the previous result factory
Provider = Dbproviderfactories.getfactory (providername);
You can use this instance to create the corresponding Connection,command and Adapater objects.
When you are debugging, you can see that these objects have become the corresponding database type
CNN = provider. CreateConnection ();
Cnn. ConnectionString = configurationmanager.connectionstrings[1]. ConnectionString;
cmd = provider. CreateCommand ();
Cmd. Connection = CNN;
}
Executes a query and returns a datasheet
Public DataTable Excutequery (string querystring)
{
DataTable result = new DataTable ();
DbDataAdapter adapter = provider. Createdataadapter ();
Cmd.commandtype = CommandType.Text;
Cmd.commandtext = querystring;
Adapter. SelectCommand = cmd;
Try
{
Cnn. Open ();
Adapter. Fill (result);
}
Catch
{
result = NULL;
}
Finally
{
Cnn. Close ();
}
return result;
}
The above is just a simple application, and did not do more advanced encapsulation, only for the brothers do not know the reference.
By the way, I saw that brother's article in the morning using the Swith case statement to implement different methods of creating connection, command, and Adapater, and then said the implementation of the factory method. In fact, this is completely wrong, the factory model is proposed to avoid so many swith case caused by the trouble. Later I will have a few common patterns of the reasons and application of the situation summed up in C # to do a few examples to the unclear brother posted.