CYQ.Data V5 从入门到放弃ORM系列:教程 - MProc类使用

时间:2022-06-07 07:59:44

MProc介绍

MProc:是一个用于执行SQL或存储过程的数据库操作类,它轻量高性能地类似于Dapper。

MProc:它出现的场景很少,因为MAction自身就能处理掉90%-100%的数据操作(以存储过程为核心操作的除外)

MProc项目Demo

1:项目图:只有一个控制台代码,说明此类的使用极度简单。

CYQ.Data V5 从入门到放弃ORM系列:教程 - MProc类使用

2:示例代码:

   class Program
{ static void Main(string[] args)
{
//MAction已经演示了配置文件配置链接,这里就用代码了。
AppConfig.DB.DefaultConn = "Data Source={0}demo.db;failifmissing=false;";
ExeSql();
ExeProc();
Console.Read();
}
static void OutMsg(object msg)
{
Console.WriteLine(msg.ToString());
}
/// <summary>
/// 执行SQL语句
/// </summary>
static void ExeSql()
{
//AppConfig.DB.DefaultConn = "server=CYQ-PC\\SQL2008;database=Test;uid=sa;pwd=123456";
string sql = "select * from users";
using (MProc proc = new MProc(sql))
{
proc.BeginTransation();//事务的使用和MAction是一样的 MDataTable dt = proc.ExeMDataTable();
OutMsg(dt.Rows.Count); proc.ResetProc("select name from users where UserID=@UserID");
proc.Set("UserID", );
string name = proc.ExeScalar<string>();
OutMsg(name); proc.ResetProc("update users set password=123 where name=@name");
proc.Set("name", name);
int result = proc.ExeNonQuery();
OutMsg(result); if (result < )
{
proc.RollBack();//找不到结果,要回滚事务
return;
} proc.ResetProc("select * from users;select * from Article");//多语句执行
List<MDataTable> dtList = proc.ExeMDataTableList();
OutMsg(dtList.Count);
proc.EndTransation();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
static void ExeProc()
{
return;
//SQlite 没有存储过程,只能写示例代码
using (MProc proc = new MProc("存储过程名"))
{
proc.Set("参数1", "值1");
proc.Set("参数2", "值2");
proc.SetCustom("ReturnValue", ParaType.ReturnValue);//如果有返回值
proc.SetCustom("OutPutValue1", ParaType.OutPut);//如果有output值
proc.SetCustom("OutPutValue2", ParaType.OutPut);//如果有output值多个
proc.SetCustom("XXX", ParaType.Cursor);//如果是Oracle有游标
proc.SetCustom("XXX2", ParaType.CLOB);//Oracle的CLOB类型
proc.SetCustom("XXX3", ParaType.NCLOB);//Oracle的NCLOB类型
MDataTable dt = proc.ExeMDataTable();//执行语句
int returnValue = proc.ReturnValue;//拿返回值
object outPutValue = proc.OutPutValue;//如果只有一个值
Dictionary<string,string> dic=proc.OutPutValue as Dictionary<string,string>;
string out1 = dic["OutPutValue1"];
string out2 = dic["OutPutValue2"];
}
}
}

3:代码说明:

1:MProc的参数判断是存储过程还是SQL语句是按空格判断的。

2:如果你的SQL语句是select%20*%20from...将空格转义,会被判断为存储过程的。

3:如果你真要这么整,第三个参数isFixProc可以设置为false或true来指定是SQL或存储过程。

4:存储过程时:特殊的参数在SetCustom里设置。

5:返回值、OutPut值,都是在执行后才拿值的。(以前有人在执行前就拿值,弄的我不知道怎么解释)

总结:

1:Demo的SVN下载地址:http://code.taobao.org/svn/cyqopen/trunk/CYQ.Data.GettingStarted/

2:谢谢支持!