首页 > 代码库 > C# 数据实现设计模式

C# 数据实现设计模式

一个人没事,写了一个底层数据实现读取设计模式,个人觉得还是蛮好扩展,里面有不足的地方希望大家给予指导。话不多说先看个图吧!图可能不正规,伤害了你的眼睛见谅。有图有真相

其实这个设计模式,就是一个简单的创建模式。什么是创建模式,我就简单的说一下,利用创建者模式可以创建出不同类型的产品。

首先我定义了一个SqlDB类这个类是实现数据连接以及Sql语句处理的类。SqlHelper类是存放sql语句的。Model是存放数据表字段封装的模型。IExcuteData是个泛型接口,通过这个接口可以得到不同模型类的一条数据。ExecuteData<T> 是个泛型类。不好意图忘了画。通过这个泛型类获得模型所有数据以及执行sql的语句其他语句。接下来我们就看看代码吧。

public static class SqlHelper
{

public const string Coumn_FOREIGNTRAIN_TrainID = "TrainID";
public const string Coumn_FOREIGNTRAIN_EmployeeNo = "EmployeeNo";
public const string Coumn_FOREIGNTRAIN_EmployeeName = "EmployeeName";
public const string Coumn_FOREIGNTRAIN_CourseNo = "CourseNo";
public const string Coumn_FOREIGNTRAIN_CredentialsNo = "CredentialsNo";
public const string Coumn_FOREIGNTRAIN_Credentials = "Credentials";
public const string Coumn_FOREIGNTRAIN_IDNumber = "IDNumber";
public const string Coumn_FOREIGNTRAIN_GetCourse = "GetCourse";
public const string Coumn_FOREIGNTRAIN_Unit = "Unit";
public const string Coumn_FOREIGNTRAIN_Qualified = "Qualified";
public const string Coumn_FOREIGNTRAIN_Isdelete = "Isdelete";
public const string Coumn_FOREIGNTRAIN_CreatDate = "CreatDate";
public const string Coumn_FOREIGNTRAIN_TrainNo = "TrainNo";
public const string Coumn_FOREIGNTRAIN_Explain = "Explain";

public const string Sql_FOREIGNTRAIN_GetAll = "select * from T_TMS_FOREIGNTRAIN where Isdelete=1 order by CreatDate desc";
public const string Sql_FOREIGNTRAIN_Add = "insert [dbo].[T_TMS_FOREIGNTRAIN](TrainID,EmployeeNo,EmployeeName,CourseNo,CredentialsNo" +
",Credentials,IDNumber,GetCourse,Unit,Isdelete,Qualified,CreatDate,TrainNo,Explain)" +
"values(‘{0}‘,{1},‘{2}‘,‘{3}‘,‘{4}‘,‘{5}‘,‘{6}‘,‘{7}‘,‘{8}‘,{9},‘{10}‘,‘{11}‘,‘{12}‘,‘{13}‘)";
public const string Sql_FOREIGNTRAIN_DeleteById = "delete from T_TMS_FOREIGNTRAIN where TrainID=‘{0}‘";
#region 

}

public interface IExcuteData<T>
{
  T GetInfo(DataRow dr);
}

model 模型要继承IExcuteData

public class T_TMS_FOREIGNTRAIN : DBModule.IExcuteData<T_TMS_FOREIGNTRAIN>
{
public T_TMS_FOREIGNTRAIN()
{ }
private string _trainid;
private int? _employeeno;
private string _employeename;
private string _courseno;
private string _credentialsno;
private string _credentials;
private string _idnumber;
private string _getcourse;
private string _unit;
private int? _isdelete;
private string _qualified;
private DateTime? _creatDate;
private string _trainNo;
private string _Explain;

public string Explain
{
get { return _Explain; }
set { _Explain = value; }
}

public string TrainNo
{
get { return _trainNo; }
set { _trainNo = value; }
}

public DateTime? CreatDate
{
get { return _creatDate; }
set { _creatDate = value; }
}
/// <summary>
///
/// </summary>
public string TrainID
{
set { _trainid = value; }
get { return _trainid; }
}
/// <summary>
///
/// </summary>
public int? EmployeeNo
{
set { _employeeno = value; }
get { return _employeeno; }
}
/// <summary>
///
/// </summary>
public string EmployeeName
{
set { _employeename = value; }
get { return _employeename; }
}
/// <summary>
///
/// </summary>
public string CourseNo
{
set { _courseno = value; }
get { return _courseno; }
}
/// <summary>
///
/// </summary>
public string CredentialsNo
{
set { _credentialsno = value; }
get { return _credentialsno; }
}
/// <summary>
///
/// </summary>
public string Credentials
{
set { _credentials = value; }
get { return _credentials; }
}
/// <summary>
///
/// </summary>
public string IDNumber
{
set { _idnumber = value; }
get { return _idnumber; }
}
/// <summary>
///
/// </summary>
public string GetCourse
{
set { _getcourse = value; }
get { return _getcourse; }
}
/// <summary>
///
/// </summary>
public string Unit
{
set { _unit = value; }
get { return _unit; }
}
/// <summary>
///
/// </summary>
public string Qualified
{
get { return _qualified; }
set { _qualified = value; }
}
/// <summary>
///
/// </summary>
public int? Isdelete
{
set { _isdelete = value; }
get { return _isdelete; }
}

#region IExcuteData<T_TMS_FOREIGNTRAIN> 成员

public T_TMS_FOREIGNTRAIN GetInfo(System.Data.DataRow dr)
{
T_TMS_FOREIGNTRAIN info = null;
if (dr != null)
{
info = new T_TMS_FOREIGNTRAIN();
info.CourseNo =PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_CourseNo]);
info.Credentials=PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_Credentials]);
info.CredentialsNo=PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_CredentialsNo]);
info.EmployeeName=PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_EmployeeName]);
info.EmployeeNo = PrettiChose.Convert.Getint(dr[SqlHelper.Coumn_FOREIGNTRAIN_EmployeeNo]);
info.GetCourse = PrettiChose.Convert.GetDateTimebystring(dr[SqlHelper.Coumn_FOREIGNTRAIN_GetCourse].ToString()).ToString("yyyy/MM/dd");
info.IDNumber = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_IDNumber]);
info.Isdelete = PrettiChose.Convert.Getint(dr[SqlHelper.Coumn_FOREIGNTRAIN_Isdelete]);
info.TrainID = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_TrainID]);
info.Unit = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_Unit]);
info.Qualified = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_Qualified]);
info.CreatDate = PrettiChose.Convert.GetDateTimebystring(dr[SqlHelper.Coumn_FOREIGNTRAIN_CreatDate].ToString());
info.TrainNo = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_TrainNo]);
info.Explain = PrettiChose.Convert.Getstring(dr[SqlHelper.Coumn_FOREIGNTRAIN_Explain]);
}

return info;
}

#endregion
}

SqlDB是数据连接处理sql语句。

public class SqlDB
{

string sqlconn = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
SqlConnection conn = null;
SqlTransaction trans = null;
public bool DbOpen()
{
bool btrn = false;
try
{
conn = new SqlConnection(sqlconn);
conn.Open();
btrn = true;
}
catch (Exception ex)
{
}
return btrn;
}
/// <summary>
/// 开始事物
/// </summary>
/// <returns></returns>
public bool DbOpenTransaction()
{
bool btrn = false;
try
{
conn = new SqlConnection(sqlconn);
conn.Open();
trans = conn.BeginTransaction();
btrn = true;
}
catch (Exception ex)
{

}

return btrn;
}
/// <summary>
/// 提交事物
/// </summary>
public void CommitTransaction()
{
trans.Commit();
}
/// <summary>
/// 释放事物
/// </summary>
public void DisposeTransaction()
{
trans.Dispose();
}

/// <summary>
/// 回滚事物
/// </summary>
public void RollbackTransaction()
{
trans.Rollback();
}

public void DbClose()
{
conn.Close();
}
/// <summary>
/// 执行事务
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public bool DoTransaction(string sql)
{
bool btrn = false;
try
{
SqlCommand cmd = new SqlCommand(sql, conn, trans);
cmd.ExecuteNonQuery();
btrn = true;

}
catch (Exception ex)
{
btrn = false;

}
return btrn;
}
/// <summary>
/// 得到数据
/// </summary>
/// <param name="sql"></param>
/// <param name="sResult"></param>
/// <returns></returns>
public DataSet GetDataSet(string sql, out string sResult)
{
sResult = "";
DataSet ds = null;
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch (Exception ex)
{
sResult = ex.Message;
}
return ds;
}
/// <summary>
/// 执行插入,删除,一条导入数据
/// </summary>
/// <param name="sql"></param>
/// <param name="sResult"></param>
/// <returns></returns>
public int ExecuteBySql(string sql, out string sResult)
{
sResult = "";
int icount = 0;
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
icount = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
sResult = ex.Message;
}

return icount;
}
/// <summary>
/// 批量插入数据用的
/// </summary>
/// <param name="tablename"></param>
/// <param name="dataTable"></param>
/// <returns></returns>
public bool InsertTable(string tablename, DataTable dataTable)
{
bool trb = true;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "dbo." + tablename;

try
{
bulkCopy.WriteToServer(dataTable);

}
catch (Exception ex)
{
trb = false;
}
finally
{
bulkCopy.Close();
}
}
return trb;
}
}

ExecuteData这个类是很重要,表现成得到数据,只要调用这里GetData方法就可以了。等sql 增删改,和事物

public class ExecuteData<T> where T :new()
{

SqlDB DB = new SqlDB();
/// <summary>
/// 得到传入的类型数据
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public virtual List<T> GetData(string sql)
{
List<T> CostList = null;
if (DB.DbOpen())
{
CostList = new List<T>();
string sResqul = "";
DataSet ds = DB.GetDataSet(sql, out sResqul);
//object k = new T();
//IExcuteData<T> TData = http://www.mamicode.com/k as IExcuteData;
dynamic TConvert = new T();
IExcuteData<T> TData = http://www.mamicode.com/TConvert;
if (ds.Tables != null)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
T info = TData.GetInfo(ds.Tables[0].Rows[i]);
if (info != null)
{
CostList.Add(info);
}
}
}
DB.DbClose();
}
return CostList;
}

/// <summary>
/// 执行insert,update ,delete语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public bool ExcuteAdd_Up_del(string sql)
{
bool btr = false;
if (DB.DbOpen())
{
string sResqul = "";
if (DB.ExecuteBySql(sql, out sResqul) > 0)
{
btr = true;
}
DB.DbClose();
}
return btr;
}

/// <summary>
/// 执行事务数据
/// </summary>
/// <param name="sqllist"></param>
/// <returns></returns>
public bool DoTransaction(List<string> sqllist)
{
bool btr = false;
try
{
if (DB.DbOpenTransaction())
{
for (int i = 0; i < sqllist.Count; i++)
{
if (DB.DoTransaction(sqllist[i]))
{
btr = true;
}
else
{
DB.RollbackTransaction();
break;
}
}
DB.CommitTransaction();
DB.DisposeTransaction();
DB.DbClose();
}
}
catch
{

}
return btr;
}
}

 

接下来就是在表现层做一下事情就可以得到数据,以及处理数据

 

ExecuteData<要传入的类型> excute=new ExecuteData<要传入的类型>();

excute.GetData("要传入sql")

excute.DoTransaction(“要执行的Sql数据集合”)

excute.ExcuteAdd_Up_del("增删改sql语句")

我想给大家看的不是代码,而是这个设计的想法。设计原理,代码可以根据情况而改。