此类型的接口可以类似于如下所示:
using System; using System.Data; namespace Common { public interface IDbCustomers { DataTable GetCustomers(); DataTable GetCustomerOrders(string CustomerID); DataTable GetCustomersByCountry(string CountryCode); bool InsertCustomer(); } }
如果希望将 Microsoft® SQL Server™ 和 Microsoft® Access 作为数据源为其提供支持,则应该在 Microsoft® Visual Studio® .NET 中创建两个不同项目,每个数据源分别创建一个。
为 SQL Server 创建的项目将类似于如下所示:
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Configuration; using Common; namespace DAL { public class CustomersData : IDbCustomers { public DataTable GetCustomers() { string ConnectionString = ConfigurationSettings.AppSettings ["ConnectionString"]; using (SqlConnection cnn = new SqlConnection (ConnectionString)) { string cmdString = "SELECT CustomerID," + "CompanyName,ContactName " + "FROM Customers"; SqlCommand cmd = new SqlCommand (cmdString, cnn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable("Customers"); da.Fill(dt); return dt; } } public DataTable GetCustomerOrders(string CustomerID) { // 待定 return null; } public DataTable GetCustomersByCountry (string CountryCode) { // 待定 return null; } public bool InsertCustomer() { // 待定 return false; } } }
从 Microsoft® Access 进行数据检索的代码类似于如下所示:
using System; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Configuration; using Common; namespace DAL { public class CustomersData : IDbCustomers { public DataTable GetCustomers() { string ConnectionString = ConfigurationSettings.AppSettings ["ConnectionString"]; using (OleDbConnection cnn = new OleDbConnection (ConnectionString)) { string cmdString = "SELECT CustomerID," + "CompanyName,ContactName " + "FROM Customers"; OleDbCommand cmd = new OleDbCommand (cmdString, cnn); OleDbDataAdapter da = new OleDbDataAdapter(cmd); DataTable dt = new DataTable("Customers"); da.Fill(dt); return dt; } } public DataTable GetCustomerOrders(string CustomerID) { // 待定 return null; } public DataTable GetCustomersByCountry (string CountryCode) { // 待定 return null; } public bool InsertCustomer() { // 待定 return false; } } }CustomersData 类实现 IdbCustomers 接口。需要支持新数据源时,只能创建一个实现该接口的新类。