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

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<string, object> parameters)
        {
            System.Data.Common.DbCommand cmd = connection.CreateCommand();
            cmd.CommandText = sql;
            if (parameters != null)
            {
                foreach (KeyValuePair<string, object> 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<string,object> parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return GetCommand(sql, parameters).ExecuteNonQuery();
            }     
        }

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

public object ExecuteReader(string sql, Dictionary<string, object> 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<string, object> parameters)
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToTable(GetCommand(sql, parameters).ExecuteReader());
            }
        }

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

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

public List<T> ExcuteList<T>()
        {
            using (connection)
            {
                connection.ConnectionString = cnnstr;
                connection.Open();
                return DbHelper.ToList<T>(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<string, object> 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<T> ToList<T>(System.Data.IDataReader reader) 
        {
            List<T> list = new List<T>();
            Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
            while (sr.Read())
            {
                T t = Activator.CreateInstance<T>();
                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<T>(System.Data.IDataReader reader)
        {
            Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
            while (sr.Read())
            {
                T t = Activator.CreateInstance<T>();
                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<T> TableToList<T>(System.Data.DataTable dt) 
        {
            return ToList<T>(dt.CreateDataReader());
        }

public static System.Data.DataTable ListToTable<T>(IList<T> 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>(T obj)
        {
            string tb = obj.GetType().Name;
            string SQL = "insert into {0}({1})values({2})";
            string fles = "";
            string sparam = "";
            Dictionary<string, object> dicParams = new Dictionary<string, object>();
            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>(T obj)
        {
            string tb = obj.GetType().Name;
            string SQL = "insert into {0}({1})values({2})";
            string fles = "";
            string sparam = "";
            Dictionary<string, object> dicParams = new Dictionary<string, object>();
            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
}

(0)

相关推荐

  • .NET(C#)连接各类数据库代码-集锦

    1.C#连接连接Access 复制代码 代码如下: using System.Data;  using System.Data.OleDb;  ..  string strConnection="Provider=Microsoft.Jet.OleDb.4.0;";  strConnection+=@"Data Source=C:BegASPNETNorthwind.mdb";  OleDbConnection objConnection=new OleDbConn

  • c#数据绑定之向查询中添加参数(.Net连接外部数据库)

    在ACCESS数据库中可以用MSSQL的形式定义操作字符串,也可以采用OLEDB的形式. MSSQL 形式 复制代码 代码如下: string sqlText = @"SELECT * FROM [User] WHERE UserName= @name"; OLEDB的形式 复制代码 代码如下: string sqlText = @"SELECT * FROM [User] WHERE UserName= ?"; 下一步是通过 OleDbCommand执行操作. 复

  • c#生成excel示例sql数据库导出excel

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Office.Interop.Excel;using System.Reflection; namespace ListToExcel{    class Program    {        static List<objtype> objs = new List<ob

  • c#连接sqlserver数据库、插入数据、从数据库获取时间示例

    c#连接sqlserver.插入数据.从数据库获取时间 复制代码 代码如下: using System;using System.Data.SqlClient; namespace Test{    //连接数据库    public class Connection    {        private static string connectionString =            "Server = 192.168.1.222;" +            "D

  • c#操作sqlserver数据库的简单示例

    1.在用windows模式登陆sql server 数据库 简历一个student的数据库,然后新建查询: 复制代码 代码如下: create table student( id     int  auto_increment  primary key, name char(10) not null, sex    char(10) not null, age   char(10) not null,   ) 2.在vs中新建一个项目,输入一下代码: 复制代码 代码如下: using Syste

  • C# Oracle数据库操作类实例详解

    本文所述为C#实现的Oracle数据库操作类,可执行超多常用的Oracle数据库操作,包含了基础数据库连接.关闭连接.输出记录集.执行Sql语句,返回带分页功能的dataset .取表里字段的类型和长度等,同时还有哈稀表自动插入数据库等高级任务.需要特别指出的是:在执行SQL语句,返回 DataReader之前一定要先用.read()打开,然后才能读到数据,再用hashTable对数据库进行insert,update,del操作,注意此时只能用默认的数据库连接"connstr". 完整

  • c#连接access数据库操作类分享

    1.配置web.config文件:配置数据库连接参数(根据实际情况设置数据库路径和密码) 复制代码 代码如下: <configuration><appSettings/><connectionStrings><add name="ConnectionString" connectionString="PRovider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\keleyi\App_Data\db.m

  • C#数据库操作类AccessHelper实例

    本文实例讲述了C#数据库操作类AccessHelper.分享给大家供大家参考. 具体实现方法如下: 复制代码 代码如下: using System; using System.Data; using System.Configuration; using System.Data.OleDb; using ahwildlife.Utils; /// <summary> /// AccessHelper 的摘要说明 /// </summary> public class AccessH

  • 数据库 数据类型float到C#类型decimal, float数据类型转化无效

    今天运行系统突然出错,数据类型转化无效,错误在system.data.sqlclient.get_decimal()方法,初步估计是数据库的float类型转换为c#的decimal类型时出错了,实体类使用的是decimal?类型,心想就算数据库里的数值是空,也不能出现转换错误啊. 网上百般搜索,很多人遇到类似情况,多数是直接去float类型时候出错,如(float)dr[0],后来看到有说应该是先转化成double,然后在转化成float就可以了 尝试了一下把实体类的decimal?类型的字段改

  • C#使用DataSet Datatable更新数据库的三种实现方法

    本文以实例形式讲述了使用DataSet Datatable更新数据库的三种实现方法,包括CommandBuilder 方法.DataAdapter 更新数据源以及使用sql语句更新.分享给大家供大家参考之用.具体方法如下: 一.自动生成命令的条件 CommandBuilder 方法 a)动态指定 SelectCommand 属性 b)利用 CommandBuilder 对象自动生成 DataAdapter 的 DeleteCommand.InsertCommand 和 UpdateCommand

  • c# 数据库的 sql 参数封装类的编写

    数据库的 sql 参数封装类的编写 复制代码 代码如下: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI

随机推荐