网络编程
位置:首页>> 网络编程>> 数据库>> 在SQL Server中编写通用数据访问方法(2)

在SQL Server中编写通用数据访问方法(2)

作者:doorsir 来源:赛迪网技术社区 发布时间:2009-01-20 11:35:00 

标签:

该类的作用是向应用程序的较高级别隐藏与创建特定类型(来自特定的数据提供程序)的实例有关的细节,应用程序现在可以使用通过基本接口公开的一般行为与数据源进行交互。

让我们了解一下如何从应用程序的其他部分使用该类:

using System;
using System.Data;
using System.Data.Common;
using System.Configuration;   

namespace DAL
{
   public class CustomersData
   {
      public DataTable GetCustomers()
      {
         string ConnectionString =
            ConfigurationSettings.AppSettings
            ["ConnectionString"];
         DatabaseType dbtype =
            (DatabaseType)Enum.Parse
            (typeof(DatabaseType),
            ConfigurationSettings.AppSettings
            ["DatabaseType"]);

         IDbConnection cnn =
            DataFactory.CreateConnection
            (ConnectionString,dbtype);

         string cmdString = "SELECT CustomerID" +
            ",CompanyName,ContactName FROM Customers";

         IDbCommand cmd =
            DataFactory.CreateCommand(
            cmdString, dbtype,cnn);

            DbDataAdapter da =
               DataFactory.CreateAdapter(cmd,dbtype);

         DataTable dt = new DataTable("Customers");

         da.Fill(dt);

         return dt;
      }
       
      public CustomersDS GetCustomerOrders(string CustomerID)
      {
         // 待定
         return null;
      }
      public CustomersList GetCustomersByCountry
         (string CountryCode)
      {
         // 待定
         return null;
      }
      public bool InsertCustomer()
      {
         // 待定
         return false;
      }
   }
}

 
在 CustomerData 类的 GetCustomers() 方法中,我们可以看到通过读取配置文件中的信息。可以使用 DataFactory 类通过特定连接字符串创建 XxxConnection 实例,并编写与基本数据源没有特定依赖性的其余代码部分。

与数据层交互的一个业务层类示例看起来可能类似下面这样:

using System;
using System.Data;
using DAL;

namespace BLL
{
    public class Customers
    {
        public DataTable GetAllCustomers()
        {
            CustomersData cd = new CustomersData(); 
            DataTable dt = cd.GetCustomers();
            return dt;
        }
        public DataSet GetCustomerOrders()
        {
            // 待定
            return null;
        }
    }
}

这样看来,此方法出现什么问题了?此处的问题是,只有一个重要细节将代码绑定到特定数据源:命令字符串的 SQL 语法!实际上,如果以这种方式编写应用程序,则使其具有可移植性的唯一办法是采用可以由任何数据源解释的基本 SQL 语法,但这样可能会失去从特定数据源的特定功能获得好处的机会。如果应用程序只对数据进行很简单和很标准的操作,并且如果您不希望使用特定数据源中的高级功能(如 XML 支持),这可能是个小问题。但通常此方法将导致性能降低,因为您无法使用每个数据源的最佳特性。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com