SqlSugar-执行Sql语句查询实例

时间:2024-03-12 12:49:59

使用SqlSugar执行sql语句

1.简单查询

SqlSugarClient db = SugarContext.GetInstance();
//执行sql语句,处理
//1.执行sql,转成list
List<teacher> list1 = db.SqlQuery<teacher>("select * from teacher where tsex=@tsex", new { tsex = "" });
Console.WriteLine(list1.ToJsonString());
//2.转成dynamic
dynamic list2 = db.SqlQueryDynamic("select * from UserInfo");
Console.WriteLine(list2.Length);
//3.转成json数据
string list3 = db.SqlQueryJson("select * from UserInfo");
Console.WriteLine(list3);
//4.返回int
int count = db.SqlQuery<int>("select count(*) from UserInfo").FirstOrDefault();
Console.WriteLine(count);

//5.返回键值对类型
Dictionary<string, string> list4 = db.SqlQuery<KeyValuePair<string, string>>("select UserID,Name from UserInfo")
    .ToDictionary(q => q.Key, q => q.Value);
Console.WriteLine(list4.ToJsonString());

//6.返回List<string[]> 集合
List<string[]> list5 = db.SqlQuery<string[]>("select  * from teacher where tsex=@tsex", new { tsex = "" });
Console.WriteLine(list5.ToJsonString());

2.汇总查询

SqlSugarClient db = SugarContext.GetInstance();
//更方便的获取第一行第一列
string result1 = db.GetString(" select  name from UserInfo where UserID=@UserID", new { UserID = 1 });
Console.WriteLine(result1);
int count = db.GetInt("select count(*) from UserInfo");
Console.WriteLine(count);
double result2 = db.GetDouble("select avg(degree) from score where cno=@cno ", new System.Data.SqlClient.SqlParameter("@cno", "3-105"));
Console.WriteLine(result2);

decimal result3 = db.GetDecimal(" select avg(degree) from score");
Console.WriteLine(result3);

3.执行视图、存储过程

SqlSugarClient db = SugarContext.GetInstance();
//执行视图查询
List<student> list1 = db.SqlQuery<student>("select * from V_student");
Console.WriteLine(list1.ToJsonString());
//执行存储过程处理
var pars = SqlSugarTool.GetParameters(new { pageStart = 1, pageEnd = 5, recordCount = 0 });
//禁止清空参数
db.IsClearParameters = false;
pars[2].Direction = System.Data.ParameterDirection.Output;
List<student> list2 = db.SqlQuery<student>("exec proc_PageStudent @pageStart,@pageEnd,@recordCount output", pars);
db.IsClearParameters = true;//启用自动清空参数
var recordCount = pars[2].Value;
Console.WriteLine(list2.ToJsonString());
Console.WriteLine(recordCount);

 

更多参考:

SqlSugar-事务操作

SqlSugar常用增删改操作

SqlSugar常用查询实例-拉姆达表达式

SqlSugar框架T4模板的使用

.Net开源SqlServer ORM框架SqlSugar整理