ShadowSql专职拼写sql,要想做为ORM就必要借高人之手
我们要借的就是Dapper,Dapper以高性能著称,ShadowSql搭配Dapper就是强强联手
为此本项目内置了一个子项目Dapper.Shadow就是Dapper扩展
以下是Dapper.Shadow的示例
一、配置Dapper实行器- ISqlEngine engine = new SqliteEngine();
- IDbConnection connection = new SqliteConnection("Data Source=file::memory:;Cache=Shared");
- IExecutor executor = new DapperExecutor(engine, connection);
复制代码 其中engine数据库(及方言)的配置对象,现在支持5种,分别是MsSql、MySql、Oracle、Postgres和Sqlite
实现ISqlEngine可以自定义数据库范例大概方言的支持
二、读取整张表- var students = Executor.From("Students")
- .ToDapperSelect()
- .Get<Student>();
复制代码 三、查询数据
1、SqlQuery查询数据- var students = Executor.From("Students")
- .ToSqlQuery()
- .Where("Age=10")
- .ToDapperSelect()
- .Get<Student>();
复制代码- var students = Executor.From("Students")
- .ToSqlQuery()
- .ColumnValue("Age", 10)
- .ToDapperSelect()
- .Get<Student>();
复制代码- var table = new StudentTable("Students");
- var students = table.ToSqlQuery()
- .Where(table.Age.EqualValue(10))
- .ToSelect()
- .Get<Student>(Executor);
复制代码- var students = new StudentTable("Students")
- .ToSqlQuery()
- .Where(table => table.Age.EqualValue(10))
- .ToSelect()
- .Get<Student>(Executor);
复制代码- var students = new Table("Students")
- .DefineColums("Age")
- .ToSqlQuery()
- .Where(student => student.Column("Age").EqualValue(10))
- .ToDapperSelect(Executor)
- .Get<Student>();
复制代码 重要分以下三种
1.1 把实行器当数据库对象,如许查询就自带实行器,可以直接实行
1.2 实行时把实行器当参数传入
1.3 先查询,调用ToDapperSelect创建可实行对象
2、Query查询数据- var table = new StudentTable("Students");
- var students = table.ToQuery()
- .And(table.Age.EqualValue(10))
- .ToSelect()
- .Get<Student>(Executor);
复制代码- var students = Executor.From("Students")
- .ToQuery()
- .And(table => table.Field("Age").EqualValue(10))
- .ToDapperSelect()
- .Get<Student>();
复制代码- var table = new StudentTable("Students");
- var students = table.ToQuery()
- .And(table.Age.EqualValue(10))
- .ToDapperSelect(Executor)
- .Get<Student>();
复制代码
查询方式多样,限与篇幅没法逐一
以上示例邮件可以清晰显示ShadowSql和Dapper可以无缝对接
四、查询数据百变邪术,值变参数
看以下示例,我们只是用ParametricExecutor代替DapperExecutor- var connection = new SqliteConnection("Data Source=file::memory:;Cache=Shared");
- var excutor = new ParametricExecutor(new SqliteEngine(), connection);
- var students = excutor.From("Students")
- .ToQuery()
- .And(table => table.Field("Age").EqualValue(10))
- .ToDapperSelect()
- .Get<Student>();
复制代码
查询照旧正常的,但调试到Dapper内部,看sql发生了变革。
本来sql应该是SELECT * FROM "Students" WHERE "Age"=10变成了SELECT * FROM "Students" WHERE "Age"=@p1
本来参数应该是默认值null的,结果填充了参数p1,值为10
做过sql注入安全的同砚应该很清楚查询值为字符串导致sql注入的风险
尽管该工具对字符串查询值有做过滤的规则,但我们知道这还远远不够
我们应该对字符串查询全部用参数化,但这可能增长了太多工作量,特别是接手祖传的老项目
这个邪术就可以解决这个棘手的问题
以上是用Query举例,用SqlQuery也是同理,ParametricExecutor会把查询值转为参数化查询,并与传入的参数做合并
就如许实现了一个精简别致的高性能ORM,您也可以使用ShadowSql和Dapper来DIY属于本身的高性能ORM
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|