PetShop 4.0 精简化的分层代码

本文介绍了一个订单系统的架构设计及其实现细节,包括业务逻辑层、数据访问层工厂、配置文件设置等内容,展示了如何通过分层架构实现订单的增删改查等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

namespace PetShop.BLL
{
    public class Order {
        private static readonly IOrder dal = PetShop.DALFactory.DataAccess.CreateOrder();
        public OrderInfo GetOrder(int orderId) {
            return dal.GetOrder(orderId);
        }
    }
}

namespace PetShop.DALFactory {
    public sealed class DataAccess {
        private static readonly string orderPath = ConfigurationManager.AppSettings["OrdersDAL"];
             public static PetShop.IDAL.IOrder CreateOrder() {
            string className = orderPath + ".Order";
            return (PetShop.IDAL.IOrder)Assembly.Load(orderPath).CreateInstance(className);
        }
    }
}

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <connectionStrings>
        <!-- SQL connection string for Orders database-->
        <add name="SQLConnString3" connectionString="server=(local);user id=sa;password=sa;database=MSPetShop4Orders;min pool size=4;max pool size=4;packet size=1024" providerName="System.Data.SqlClient"/>
        </connectionStrings>
    <appSettings>
        <!-- Pet Shop DAL configuration settings -->
        <!--设置数据库连接类型  value 此数据库联接类 -->
        <add key="OrdersDAL" value="PetShop.SQLServerDAL"/>
    </appSettings>
    <system.web>
</configuration>

namespace PetShop.IDAL{
    public interface IOrder {
        OrderInfo GetOrder(int orderId);
    }
}

using System;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Text;
using PetShop.Model;
using PetShop.IDAL;
using PetShop.DBUtility;

namespace PetShop.SQLServerDAL {

    public class Order : IOrder {
        private const string SQL_INSERT_ORDER = "Declare @ID int; Declare @ERR int; INSERT INTO Orders VALUES(@UserId, @Date, @ShipAddress1, @ShipAddress2, @ShipCity, @ShipState, @ShipZip, @ShipCountry, @BillAddress1, @BillAddress2, @BillCity, @BillState, @BillZip, @BillCountry, 'UPS', @Total, @BillFirstName, @BillLastName, @ShipFirstName, @ShipLastName, @AuthorizationNumber, 'US_en'); SELECT @ID=@@IDENTITY; INSERT INTO OrderStatus VALUES(@ID, @ID, GetDate(), 'P'); SELECT @ERR=@@ERROR;";
        private const string SQL_INSERT_ITEM = "INSERT INTO LineItem VALUES( ";
        private const string SQL_SELECT_ORDER = "SELECT o.OrderDate, o.UserId, o.CardType, o.CreditCard, o.ExprDate, o.BillToFirstName, o.BillToLastName, o.BillAddr1, o.BillAddr2, o.BillCity, o.BillState, BillZip, o.BillCountry, o.ShipToFirstName, o.ShipToLastName, o.ShipAddr1, o.ShipAddr2, o.ShipCity, o.ShipState, o.ShipZip, o.ShipCountry, o.TotalPrice, l.ItemId, l.LineNum, l.Quantity, l.UnitPrice FROM Orders as o, lineitem as l WHERE o.OrderId = @OrderId AND o.orderid = l.orderid";
        private const string PARM_USER_ID = "@UserId";
        private const string PARM_DATE = "@Date";
        private const string PARM_SHIP_ADDRESS1 = "@ShipAddress1";
        private const string PARM_SHIP_ADDRESS2 = "@ShipAddress2";
        private const string PARM_SHIP_CITY = "@ShipCity";
        private const string PARM_SHIP_STATE = "@ShipState";
        private const string PARM_SHIP_ZIP = "@ShipZip";
        private const string PARM_SHIP_COUNTRY = "@ShipCountry";
        private const string PARM_BILL_ADDRESS1 = "@BillAddress1";
        private const string PARM_BILL_ADDRESS2 = "@BillAddress2";
        private const string PARM_BILL_CITY = "@BillCity";
        private const string PARM_BILL_STATE = "@BillState";
        private const string PARM_BILL_ZIP = "@BillZip";
        private const string PARM_BILL_COUNTRY = "@BillCountry";
        private const string PARM_TOTAL = "@Total";
        private const string PARM_BILL_FIRST_NAME = "@BillFirstName";
        private const string PARM_BILL_LAST_NAME = "@BillLastName";
        private const string PARM_SHIP_FIRST_NAME = "@ShipFirstName";
        private const string PARM_SHIP_LAST_NAME = "@ShipLastName";
        private const string PARM_AUTHORIZATION_NUMBER = "@AuthorizationNumber";  
        private const string PARM_ORDER_ID = "@OrderId";
        private const string PARM_LINE_NUMBER = "@LineNumber";
        private const string PARM_ITEM_ID = "@ItemId";
        private const string PARM_QUANTITY = "@Quantity";
        private const string PARM_PRICE = "@Price";

        public void Insert(OrderInfo order) {
            StringBuilder strSQL = new StringBuilder();

            // Get each commands parameter arrays
            SqlParameter[] orderParms = GetOrderParameters();

            SqlCommand cmd = new SqlCommand();

            // Set up the parameters
            orderParms[0].Value = order.UserId;
            orderParms[1].Value = order.Date;
            orderParms[2].Value = order.ShippingAddress.Address1;
            orderParms[3].Value = order.ShippingAddress.Address2;
            orderParms[4].Value = order.ShippingAddress.City;
            orderParms[5].Value = order.ShippingAddress.State;
            orderParms[6].Value = order.ShippingAddress.Zip;
            orderParms[7].Value = order.ShippingAddress.Country;
            orderParms[8].Value = order.BillingAddress.Address1;
            orderParms[9].Value = order.BillingAddress.Address2;
            orderParms[10].Value = order.BillingAddress.City;
            orderParms[11].Value = order.BillingAddress.State;
            orderParms[12].Value = order.BillingAddress.Zip;
            orderParms[13].Value = order.BillingAddress.Country;
            orderParms[14].Value = order.OrderTotal;
            orderParms[15].Value = order.BillingAddress.FirstName;
            orderParms[16].Value = order.BillingAddress.LastName;
            orderParms[17].Value = order.ShippingAddress.FirstName;
            orderParms[18].Value = order.ShippingAddress.LastName;
            orderParms[19].Value = order.AuthorizationNumber.Value;

            foreach (SqlParameter parm in orderParms)
                cmd.Parameters.Add(parm);

            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringOrderDistributedTransaction)) {

                // Insert the order status
                strSQL.Append(SQL_INSERT_ORDER);
                SqlParameter[] itemParms;
                // For each line item, insert an orderline record
                int i = 0;
                foreach (LineItemInfo item in order.LineItems) {
                    strSQL.Append(SQL_INSERT_ITEM).Append(" @ID").Append(", @LineNumber").Append(i).Append(", @ItemId").Append(i).Append(", @Quantity").Append(i).Append(", @Price").Append(i).Append("); SELECT @ERR=@ERR+@@ERROR;");

                    //Get the cached parameters
                    itemParms = GetItemParameters(i);

                    itemParms[0].Value = item.Line;
                    itemParms[1].Value = item.ItemId;
                    itemParms[2].Value = item.Quantity;
                    itemParms[3].Value = item.Price;
                    //Bind each parameter
                    foreach (SqlParameter parm in itemParms)
                        cmd.Parameters.Add(parm);
                    i++;
                }

                conn.Open();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSQL.Append("SELECT @ID, @ERR").ToString();

                // Read the output of the query, should return error count
                using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) {
                    // Read the returned @ERR
                    rdr.Read();
                    // If the error count is not zero throw an exception
                    if (rdr.GetInt32(1) != 0)
                        throw new ApplicationException("插入的订单数据有错误 - ROLLBACK ISSUED");
                }
                //清除内存参数
                cmd.Parameters.Clear();
            }
        }


        public OrderInfo GetOrder(int orderId) {

            OrderInfo order = new OrderInfo();

            //Create a parameter
            SqlParameter parm = new SqlParameter(PARM_ORDER_ID, SqlDbType.Int);
            parm.Value = orderId;

            //Execute a query to read the order
            using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringOrderDistributedTransaction, CommandType.Text, SQL_SELECT_ORDER, parm)) {

                if (rdr.Read()) {

                    //Generate an order header from the first row
                    AddressInfo billingAddress = new AddressInfo(rdr.GetString(5), rdr.GetString(6), rdr.GetString(7), rdr.GetString(8), rdr.GetString(9), rdr.GetString(10), rdr.GetString(11), rdr.GetString(12), null, "email");
                    AddressInfo shippingAddress = new AddressInfo(rdr.GetString(13), rdr.GetString(14), rdr.GetString(15), rdr.GetString(16), rdr.GetString(17), rdr.GetString(18), rdr.GetString(19), rdr.GetString(20), null, "email");

                    order = new OrderInfo(orderId, rdr.GetDateTime(0), rdr.GetString(1), null, billingAddress, shippingAddress, rdr.GetDecimal(21), null, null);

                    IList<LineItemInfo> lineItems = new List<LineItemInfo>();
                    LineItemInfo item = null;

                    //Create the lineitems from the first row and subsequent rows
                    do {
                        item = new LineItemInfo(rdr.GetString(22), string.Empty, rdr.GetInt32(23), rdr.GetInt32(24), rdr.GetDecimal(25));
                        lineItems.Add(item);
                    } while (rdr.Read());

                    order.LineItems = new LineItemInfo[lineItems.Count];
                    lineItems.CopyTo(order.LineItems, 0);
                }
            }

            return order;
        }

        private static SqlParameter[] GetOrderParameters() {
            SqlParameter[] parms = SqlHelper.GetCachedParameters(SQL_INSERT_ORDER);

            if (parms == null) {
                parms = new SqlParameter[] {
                    new SqlParameter(PARM_USER_ID, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_DATE, SqlDbType.DateTime, 12),
                    new SqlParameter(PARM_SHIP_ADDRESS1, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_ADDRESS2, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_CITY, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_STATE, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_ZIP, SqlDbType.VarChar, 50),
                    new SqlParameter(PARM_SHIP_COUNTRY, SqlDbType.VarChar, 50),
                    new SqlParameter(PARM_BILL_ADDRESS1, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_BILL_ADDRESS2, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_BILL_CITY, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_BILL_STATE, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_BILL_ZIP, SqlDbType.VarChar, 50),
                    new SqlParameter(PARM_BILL_COUNTRY, SqlDbType.VarChar, 50),
                    new SqlParameter(PARM_TOTAL, SqlDbType.Decimal, 8),
                    new SqlParameter(PARM_BILL_FIRST_NAME, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_BILL_LAST_NAME, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_FIRST_NAME, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_SHIP_LAST_NAME, SqlDbType.VarChar, 80),
                    new SqlParameter(PARM_AUTHORIZATION_NUMBER, SqlDbType.Int)};

                SqlHelper.CacheParameters(SQL_INSERT_ORDER, parms);
            }

            return parms;
        }

        private static SqlParameter[] GetItemParameters(int i) {
            SqlParameter[] parms = SqlHelper.GetCachedParameters(SQL_INSERT_ITEM + i);

            if (parms == null) {
                parms = new SqlParameter[] {
                    new SqlParameter(PARM_LINE_NUMBER + i, SqlDbType.Int, 4),
                    new SqlParameter(PARM_ITEM_ID+i, SqlDbType.VarChar, 10),
                    new SqlParameter(PARM_QUANTITY+i, SqlDbType.Int, 4),
                    new SqlParameter(PARM_PRICE+i, SqlDbType.Decimal, 8)};

                SqlHelper.CacheParameters(SQL_INSERT_ITEM + i, parms);
            }

            return parms;
        }
    }
}

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace PetShop.DBUtility {
    public abstract class SqlHelper {
        public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString)) {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return reader;
            }
            catch {
                conn.Close();
                throw;
            }
        }

        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString)) {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        public static SqlParameter[] GetCachedParameters(string cacheKey) {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
            if (cachedParms == null)
                return null;
            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
            return clonedParms;
        }

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null) {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
    }
}

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

namespace PetShop.DBUtility {

    public abstract class SqlHelper {
        public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString;
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString)) {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return reader;
            }
            catch {
                conn.Close();
                throw;
            }
        }

        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection connection = new SqlConnection(connectionString)) {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        public static SqlParameter[] GetCachedParameters(string cacheKey) {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
            if (cachedParms == null)
                return null;
            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
            return clonedParms;
        }

 
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null) {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
    }
}

namespace PetShop.Model {
    [Serializable]
    public class OrderInfo {

        private int orderId;
        private DateTime date;
        private string userId;
        private CreditCardInfo creditCard;
        private AddressInfo billingAddress;
        private AddressInfo shippingAddress;
        private decimal orderTotal;
        private LineItemInfo[] lineItems;
        private Nullable<int> authorizationNumber;

        public OrderInfo() { }

        public OrderInfo(int orderId, DateTime date, string userId, CreditCardInfo creditCard, AddressInfo billing, AddressInfo shipping, decimal total, LineItemInfo[] line, Nullable<int> authorization) {
            this.orderId = orderId;
            this.date = date;
            this.userId = userId;
            this.creditCard = creditCard;
            this.billingAddress = billing;
            this.shippingAddress = shipping;
            this.orderTotal = total;
            this.lineItems = line;
            this.authorizationNumber = authorization;
        }

        public int OrderId {
            get { return orderId; }
            set { orderId = value; }
        }

        public DateTime Date {
            get { return date; }
            set { date = value; }
        }

        public string UserId {
            get { return userId; }
            set { userId = value; }
        }

        public CreditCardInfo CreditCard {
            get { return creditCard; }
            set { creditCard = value; }
        }

        public AddressInfo BillingAddress {
            get { return billingAddress; }
            set { billingAddress = value; }
        }

        public AddressInfo ShippingAddress {
            get { return shippingAddress; }
            set { shippingAddress = value; }
        }

        public decimal OrderTotal {
            get { return orderTotal; }
            set { orderTotal = value; }
        }

        public LineItemInfo[] LineItems {
            get { return lineItems; }
            set { lineItems = value; }
        }

        public Nullable<int> AuthorizationNumber {
            get {return authorizationNumber;}
            set {authorizationNumber = value;}
        }
    }
}

再举一范例如下:


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using ZiGoo.Model;
using ZiGoo.IDAL;
namespace ZiGoo.SQLServerDAL
{
    public class Human:IHuman
    {
        public IList<HumanInfo> GetAll()
        {
            IList<HumanInfo> list = new List<HumanInfo>();
            using (SqlConnection sqlConn = new SqlConnection())
            {
                sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString1"].ConnectionString;
                if (sqlConn.State == System.Data.ConnectionState.Closed)
                {
                    sqlConn.Open(); 
                }
                using (SqlCommand cmd = sqlConn.CreateCommand())
                {
                    cmd.CommandText = "SELECT id,name,age FROM Human";
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        int id = (int)reader["id"];
                        string name = reader["name"].ToString();
                        int? age = DBNull.Value.Equals(reader["age"]) ? null : (int?)reader["age"];
                        HumanInfo info = new HumanInfo() { Id = id, Name = name, Age = age };
                        list.Add(info);
                    }
                }
            }
            return list;
        }

    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZiGoo.IDAL;
using ZiGoo.Model;
using MySql.Data.MySqlClient;
using System.Configuration;
namespace ZiGoo.MySQLDAL
{
    public class Human : IHuman
    {
        public IList<HumanInfo> GetAll()
        {
            IList<HumanInfo> list = new List<HumanInfo>();
            using (MySqlConnection mysqlConn = new MySqlConnection())
            {
                mysqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["testdbConnectionString2"].ConnectionString;
                if (mysqlConn.State == System.Data.ConnectionState.Closed)
                {
                    mysqlConn.Open();
                }
                using (MySqlCommand cmd = mysqlConn.CreateCommand())
                {
                    cmd.CommandText = "SELECT id,name,age FROM Human";
                    MySqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        int id = reader.GetInt32("id");
                        string name = reader.GetString("name");
                        int? age = DBNull.Value == reader["age"] ? null : (int?)reader.GetInt32("age");
                        HumanInfo info = new HumanInfo() {Id=id,Name=name,Age=age };
                        list.Add(info);
                    }
                }
            }
            return list;
        }
    }
 }



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZiGoo.Model
{
    public class HumanInfo
    {
        private int? age;
        public int Id{get;set;}
        public string Name { get; set; } //本身支持null值
        public Nullable<int> Age
        {
            get { return age;}
            set { age = (int?)value;}
        }
        public HumanInfo() { }
    
    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;
namespace ZiGoo.DALFactory
{
    public sealed class DataAccess
    {
        private static readonly string humanSQLServerPath = ConfigurationManager.AppSettings["HumanSQLServerDAL"];//ZiGoo.SQLServerDAL
        private static readonly string humanMySQLPath = ConfigurationManager.AppSettings["HumanMySQLDAL"];//ZiGoo.MySQLDAL
        public static ZiGoo.IDAL.IHuman CreateSQLServerHuman()
        {
            string className = humanSQLServerPath + ".Human";
            ZiGoo.IDAL.IHuman human = (ZiGoo.IDAL.IHuman)Assembly.Load(humanSQLServerPath).CreateInstance(className);
            return human;
        }
        public static ZiGoo.IDAL.IHuman CreateMySQLHuman()
        {
            string className = humanMySQLPath + ".Human";
            ZiGoo.IDAL.IHuman human = (ZiGoo.IDAL.IHuman)Assembly.Load(humanMySQLPath).CreateInstance(className);
            return human;
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZiGoo.DALFactory;
using ZiGoo.Model;
namespace ZiGoo.BLL
{
   public static class Human
    {
        private static ZiGoo.IDAL.IHuman daSQLServer = ZiGoo.DALFactory.DataAccess.CreateSQLServerHuman();
        private static ZiGoo.IDAL.IHuman daMySQL = ZiGoo.DALFactory.DataAccess.CreateMySQLHuman();
        public static IList<HumanInfo> GetSQLServerAll()
        {
           return daSQLServer.GetAll();
        }
        public static IList<HumanInfo> GetMySQLAll()
        {
            return daMySQL.GetAll();
        }
    }
}




App.config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="testdbConnectionString1"
        connectionString="Data Source=127.0.0.1;Initial Catalog=testdb;User ID=sa;Password=123456"
        providerName="System.Data.SqlClient" />
    <add name="testdbConnectionString2"
         connectionString="server=127.0.0.1;user id=root;password=123456;persistsecurityinfo=True;database=testdb"
         providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="HumanSQLServerDAL" value="ZiGoo.SQLServerDAL"/>
    <add key="HumanMySQLDAL" value="ZiGoo.MySQLDAL"/>
  </appSettings>
</configuration>




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZiGoo.BLL;
using ZiGoo.Model;
namespace ZiGoo.HR
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        private void btnLoadSQLServer_Click(object sender, EventArgs e)
        {
            this.bindingSource1.DataSource = ZiGoo.BLL.Human.GetSQLServerAll();
        }
        private void btnLoadMySQL_Click(object sender, EventArgs e)
        {
            this.bindingSource2.DataSource = ZiGoo.BLL.Human.GetMySQLAll();
        }
    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZiGoo.Model;
namespace ZiGoo.IDAL
{
    public interface IHuman
    {
        IList<HumanInfo> GetAll();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值