实现通用的数据访问代码

ADO.NET2.0提供了一些用于通用数据访问功能开发的新的类,如DbConnection、DbCommand等,这些都被组织在System.Data.Common命名空间中。

要开发数据库无关的数据访问代码,首先应使用DbProviderFactory创建一个新的数据库提供器工厂对象:

//Create a new database provider factory
DbProviderFactory factory=DbProviderFactories.GetFactory("System.Data.SqlClient");
 

在这段代码中,因为我们传入的参数是System.Data.SqlClient,因此生成的factory对象将包括SQL Server数据库提供器工厂(术语“工厂”是指为你构建其他类的类)。在实践中,System.Data.SqlClient字符串参数是保存在配置文件中的,以使你编写的C#代码并不知道使用的是什么数据库。

数据库提供器工厂类能够通过它的CreateConnection()方法创建一个特定的数据库连接对象。因此,可以继续使用通用DbConnection来代替特定连接对象:

//Obtain a database specific connection object
DbConnection conn = factory.CreateConnection();

因此实际上,如果后端的数据库是SQL server,那连接对象实际包括的是SqlCommand对象,如果后端是数据库Oracle,那就是OracleCommand。然而,我们的程序并非是基于SqlCommand或OracleCommand对象编写的,只是简单使用DbCommand,让它在运行时自己决定在后台要创建哪种类型的对象。

在创建完连接对象后,就可以按你熟悉的方法简单地设置其属性,就像你拥有的是“常规”连接的对象那样:

//Set the connection string
conn.ConnectionString = "...connection string ...";

现在已经有了连接对象,但如何执行命令呢?正好连接对象中有一个名为CreateCommand的方法,可以返回数据库命令对象。和连接对象一样,CreateCommand()返回特定于某种数据库的命令对象,但还是可以用数据库无关的对象来代替特定于某种数据库的对象。下面这行代码就将完成任务:

//Create a database specitic command object
DbCommand comm= conn.CreateCommand();

现在,你已经拥有了一个连接对象和一个命令对象,就可以像以前一样运行它了。这边有一个相对完整的ADO.NET2.0代码段,不用知道是和哪种数据库打交道,就能把门类别表取到DataTable中:

//Create a new database provider factory
DbProviderFactory factory=DbProviderFactories.GetFactory("System.Data.SqlClient");
//Create the connection object
DbConnection conn=factory.CreateConnection();
//Initialize the connection string
conn.ConnectionString="...connection string...";
//Create the command object and set its properties
DbCommand comm= conn.CreateCommand();
comm.CommandText="GetDepartments";
comm.CommandType=CommandType.StoredProcedure;
//Open the connection
conn.Open();
//Execute the command and save the results in a DataTable
DbDataReader reader=comm.ExecuteReader();
DataTable table=new DataTable();
table.Load(reader);
//Close the reader and the connection
reader.Close();
conn.Close();
原文地址:https://www.cnblogs.com/nero/p/1617584.html