当前位置:  编程技术>.net/c#/asp.net

支持多类型数据库的c#数据库模型示例

    来源: 互联网  发布时间:2014-10-26

    本文导语:  DataAccess.cs 代码如下:using System;using System.Collections.Generic;using System.Text; namespace DynamicFramework{    public abstract class DataAccess : MarshalByRefObject    {        protected System.Data.Common.DbConnection connection;        protected string cnnstr...

DataAccess.cs

代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace DynamicFramework
{
    public abstract class DataAccess : MarshalByRefObject
    {
        protected System.Data.Common.DbConnection connection;
        protected string cnnstr = "";
        protected DataAccess()
        {
        }

        public static string ConnPath = System.Windows.Forms.Application.StartupPath + "\LocalDB.mdb";
        public static DataAccess LocalDb
        {
            get
            {
                return new OleAccess("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ConnPath);
                //return new SqlClientAccess("Server=localhost;Trusted_Connection=true;Database=RestaurantDB");
            }
        }

        public static DataAccess ServerDb
        {
            get
            {
                //return new OleAccess("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ConnPath);
                //if (Configs.LocalConfig.Instanct.IsLocalServer)
                //{

                //}
                //Trusted_Connection=true;
                //return new SqlClientAccess("Server=.;Database=RestaurantDB,uid = sa,pwd =");

                return new SqlClientAccess("Data Source=.;Initial Catalog=RestaurantDB;Persist Security Info=True;User ID=sa");
            }
        }

        private System.Data.Common.DbCommand GetCommand(string sql, Dictionary parameters)
        {
            System.Data.Common.DbCommand cmd = connection.CreateCommand();
            cmd.CommandText = sql;
            if (parameters != null)
            {
                foreach (KeyValuePair item in parameters)
                {
                    System.Data.Common.DbParameter parameter = cmd.CreateParameter();
                    parameter.ParameterName = item.Key;
                    parameter.Value = item.Value;
                    cmd.Parameters.Add(parameter);
                }
            }
            return cmd;
        }

        #region DataAccess Command

        public int ExcuteCommand(string sql,Dictionary parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return GetCommand(sql, parameters).ExecuteNonQuery();
            }     
        }

        public object ExecuteScalar(string sql, Dictionary parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return GetCommand(sql, parameters).ExecuteScalar();
            }
        }

        public object ExecuteReader(string sql, Dictionary parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return GetCommand(sql, parameters).ExecuteReader();
            }
        }


        public System.Data.DataTable ExecuteDataTable(string sql)
        {
            return ExecuteDataTable(sql, null);
        }

        public System.Data.DataTable ExecuteDataTable(string sql, Dictionary parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToTable(GetCommand(sql, parameters).ExecuteReader());
            }
        }

        public List ExcuteList(string sql, Dictionary parameters) 
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToList(GetCommand(sql, parameters).ExecuteReader());
            }
        }

        public T GetEntity(string sql, Dictionary parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToEntity(GetCommand(sql, parameters).ExecuteReader());
            }
        }

        public List ExcuteList()
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToList(GetCommand(string.Format("select * from {0}", typeof(T).Name), null).ExecuteReader());
            }
        }

        public System.Data.DataTable FillDataTable(string sql)
        {
            return FillDataTable(sql, null);
        }

        public System.Data.DataTable FillDataTable(string sql, Dictionary parameters)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            Fill(dt, GetCommand(sql, parameters));
            return dt;           
        }

        public int Fill(System.Data.DataTable dt, System.Data.Common.DbCommand cmd)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                System.Data.Common.DbDataAdapter adapter = CreateAdapter();
                adapter.SelectCommand = cmd;

                return adapter.Fill(dt);
            }
        }
        public int SaveDataTable(System.Data.DataTable dt)
        {
            return SaveDataTable(dt, dt.TableName);
        }
        public int SaveDataTable(System.Data.DataTable dt, string tableName)
        {
            return SaveTable(dt, "select * from " + tableName + " where 1 = 2");
        }

        public int SaveTable(System.Data.DataTable dt, string sql)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                System.Data.Common.DbDataAdapter adapter = CreateAdapter();
                adapter.SelectCommand = GetCommand(sql, null);
                System.Data.Common.DbCommandBuilder cmdBuild = CreateCommandBuilder();
                cmdBuild.DataAdapter = adapter;
                cmdBuild.QuotePrefix = "[";
                cmdBuild.QuoteSuffix = "]";
                return adapter.Update(dt);
            }
        }

        public int SaveDataSet(System.Data.DataSet ds)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                int updates = 0;
                foreach (System.Data.DataTable item in ds.Tables)
                {
                    updates += SaveDataTable(item);
                }
                return updates;
            }
        }

        #endregion

        internal virtual System.Data.Common.DbDataAdapter CreateAdapter()
        {
            throw new System.ApplicationException("DbDataAdapter Can Not Created!");
        }

        public virtual System.Data.Common.DbCommandBuilder CreateCommandBuilder()
        {
            throw new System.ApplicationException("DbCommandBuilder Can Not Created!");
        }


    }
}

 DbHelper.cs

 

代码如下:

 using System;
using System.Collections.Generic;
using System.Text;

namespace DynamicFramework
{
    public sealed class DbHelper
    {
        public static List ToList(System.Data.IDataReader reader) 
        {
            List list = new List();
            Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
            while (sr.Read())
            {
                T t = Activator.CreateInstance();
                Type entityType = t.GetType();
                for (int i = 0; i < sr.FieldCount; i++)
                {
                    string pName = reader.GetName(i);
                    System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
                    if (p != null)
                    {
                        p.SetValue(t, GetValue(p,sr,i), null);
                    }
                }
                list.Add(t);
            }           
            return list;
        }

        private static object GetValue(System.Reflection.PropertyInfo p,Csla.Data.SafeDataReader sr,int index)
        {
            if (p.PropertyType == typeof(string))
            {
                return sr.GetString(index);
            }
            else if (p.PropertyType == typeof(int))
            {
                return sr.GetInt32(index);
            }
            else if (p.PropertyType == typeof(decimal))
            {
                return sr.GetDecimal(index);
            }
            else if (p.PropertyType == typeof(DateTime))
            {
                return sr.GetDateTime(index);
            }
            else if (p.PropertyType == typeof(bool))
            {
                return sr.GetBoolean(index);
            }
            else if (p.PropertyType == typeof(double))
            {
                return sr.GetDouble(index);
            }
            else
            {
                return sr.GetValue(index);
            }

        }

        public static T ToEntity(System.Data.IDataReader reader)
        {
            Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
            while (sr.Read())
            {
                T t = Activator.CreateInstance();
                Type entityType = t.GetType();
                for (int i = 0; i < sr.FieldCount; i++)
                {
                    string pName = reader.GetName(i);
                    System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
                    if (p != null)
                    {
                        p.SetValue(t, GetValue(p, sr, i), null);
                    }
                }
                return t;
            }
            return default(T);
        }

        public static List TableToList(System.Data.DataTable dt) 
        {
            return ToList(dt.CreateDataReader());
        }

        public static System.Data.DataTable ListToTable(IList list)
        {
            if (list == null) return null;

            System.Data.DataTable dt = new System.Data.DataTable(typeof(T).Name);

            System.Reflection.PropertyInfo[] props = typeof(T).GetProperties();
            if (props.Length >= 0)
            {
                for (int column = 0; column < props.Length; column++)
                {
                    dt.Columns.Add(props[column].Name, props[column].PropertyType);
                }
            }
            foreach (T item in list)
            {
                System.Data.DataRow dr = dt.NewRow();
                foreach (System.Data.DataColumn column in dt.Columns)
                {
                    dr[column] = item.GetType().GetProperty(column.ColumnName).GetValue(item, null);
                }
                dt.Rows.Add(dr);
            }
            //dt.AcceptChanges();           
            return dt;
        }

        public static System.Data.DataTable ToTable(System.Data.IDataReader reader)
        {
            System.Data.DataTable dt = new System.Data.DataTable();          
            dt.Load(reader);
            return dt;
        }

        public static void SaveEntity(T obj)
        {
            string tb = obj.GetType().Name;
            string SQL = "insert into {0}({1})values({2})";
            string fles = "";
            string sparam = "";
            Dictionary dicParams = new Dictionary();
            foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
            {
                fles += var.Name + ",";
                sparam += "@" + var.Name + ",";
                dicParams.Add("@" + var.Name,var.GetValue(obj, null));
            }
            SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
            DataAccess.ServerDb.ExecuteScalar(SQL, dicParams);           
        }

        public static void SaveLocalEntity(T obj)
        {
            string tb = obj.GetType().Name;
            string SQL = "insert into {0}({1})values({2})";
            string fles = "";
            string sparam = "";
            Dictionary dicParams = new Dictionary();
            foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
            {
                fles += var.Name + ",";
                sparam += "@" + var.Name + ",";
                dicParams.Add("@" + var.Name, var.GetValue(obj, null));
            }
            SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
            DataAccess.LocalDb.ExecuteScalar(SQL, dicParams);
        }
    }


    #region DataAsss == OleDb - SqlClient - SQLite

    public class OleAccess : DataAccess
    {
        public OleAccess()
        {
            connection = new System.Data.OleDb.OleDbConnection();
        }

        public OleAccess(string connectionString)
        {
            connection = new System.Data.OleDb.OleDbConnection(connectionString);
            cnnstr = connectionString;
        }

        internal override System.Data.Common.DbDataAdapter CreateAdapter()
        {
            return new System.Data.OleDb.OleDbDataAdapter();
        }

        public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
        {
            return new System.Data.OleDb.OleDbCommandBuilder();
        }
    }

    public class SqlClientAccess : DataAccess
    {
        public SqlClientAccess()
        {
            connection = new System.Data.SqlClient.SqlConnection();
        }

        public SqlClientAccess(string connectionString)
        {
            connection = new System.Data.SqlClient.SqlConnection(connectionString);
            cnnstr = connectionString;
        }

        internal override System.Data.Common.DbDataAdapter CreateAdapter()
        {
            return new System.Data.SqlClient.SqlDataAdapter();
        }

        public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
        {
            return new System.Data.SqlClient.SqlCommandBuilder();
        }
    }

    public class SQLiteAccess : DataAccess
    {
        public SQLiteAccess()
        {
            connection = new System.Data.SQLite.SQLiteConnection();
        }

        public SQLiteAccess(string connectionString)
        {
            connection = new System.Data.SQLite.SQLiteConnection(connectionString);
            cnnstr = connectionString;
        }

        internal override System.Data.Common.DbDataAdapter CreateAdapter()
        {
            return new System.Data.SQLite.SQLiteDataAdapter();
        }

        public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
        {
            return new System.Data.SQLite.SQLiteCommandBuilder();
        }
    }


    #endregion
}
 

 


    
 
 

您可能感兴趣的文章:

  • 听说 FreeBSD 对数据库的支持不太好,但不知道对 PostgreSQL 的支持怎么样?(100分)
  • 请问jsp是否支持access数据库?如果支持,那么该怎样写代码用以实现连接???谢谢!
  • 请问Linux数据库编程是否也可以支持通用的SQL语言进行数据库编写.
  • 请问小红帽支持中文的c,c++,数据库,阿帕奇等编程吗?
  • java对什么数据库支持最好。
  • linux下不知有什么小型的数据库?要求速度比较快,开销最小。并且支持单文件数据库及多表的
  • 请问mozilla(redhat9里的)对javascript的支持程度,是否支持iframe?参与有分 iis7站长之家
  • 此数据库没有有效所有者,因此无法安装数据库关系图支持对象
  • PostgreSQL数据库基础问题,请支持!
  • 如何让我们的论坛系统全面的支持各种数据库?? 100分赠送
  • 关于数据库中文件下载的问题,小弟是java支持者!!!
  • Oracle数据库表名支持的最大长度是多少
  • 难道数据库不支持这个功能 ? 谢谢!
  • 支持多种数据库的解决方案?
  • 服务器不支持 MySql 数据库的解决方法
  • 如何创建支持FILESTREAM的数据库示例探讨
  • 我实现了个J2EE技术的服务器,支持TCP、UDP和数据库,由于性能的原因,需要改为C或C++实现,我是C、C++新手,我该如何入手呢?看什么样的
  • NaviCat连接时提示"不支持远程连接的MySql数据库"解决方法
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • c#(asp.net) 时间操作基类(支持长短日期与时间差)
  • 关于c#中枚举类型支持显示中文的扩展说明
  • 深入理解C#索引器(一种支持参数的属性)与属性的对比
  • C# 实现的图片盖章功能,支持拖拽、旋转、放缩、保存
  • Docker支持的安装方式
  • php for linux安装既不支持mysql.如何配置支持mysql
  • Ubuntu 12.04长期支持版和最新版Ubuntu 13.10下载
  • 在red hat 9.0.1支持u盘吗,支持如何驱动呀?谢了先。
  • Docker宣布支持Windows 10和Azure Windows Server
  • 到底有哪些网站支持JSP???163.com的免费空间支持吗?
  • windows10玩游戏怎么样?唯一支持DirectX 12的windows
  • 急急急,2.4.20的内核不支持pci-e,请问如何才能使其支持?
  • Docker支持更深入的容器日志分析
  • JBuilder4 能支持 Weblogic 6.0吗?怎麽支持?
  • ​Windows Server 2016提供Docker原生运行的企业级支持
  • RedHat 7.1英文版怎么样通过外挂支持中文?只要求支持......
  • nginx服务器下通过fastcgi支持php5详细安装配置步骤
  • 请问 solaris支持不支持以下几种格式的读取啊
  • HTML <strike> 标签 - HTML5 不支持
  • IE6对XML的支持比较好,但不支持JAVA……
  • HTML <tt> 标签 - HTML5 不支持
  • win7 下不支持andliunx 虚拟机,有别的支持win7的吗
  • HTML <font> 标签 - HTML5 不支持
  • 请问mozilla(redhat9里的)对javascript的支持程度,是否支持iframe?参与有分
  • HTML <basefont> 标签 - HTML5 不支持
  • JBuilderIDE中怎么才能支持鼠标的滚动轴啊?这都不支持好别扭~


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3