在SQLMAP中使用动态SQL

最近有几个同事和朋友询问如何在SQLMAP中“拼接字符串”,因为有时候条件的数量不固定,条件参数类型也不固定,无法写出 @参数名 这样的SQL语句,也就是大家常说的“动态SQL”问题。PDF.NET数据开发框架在1.0版本就支持这个功能了,而且在SQLMAP说明里面也写了,但就是没有人看

 

这里举一个实际的例子说明如何使用动态SQL。

1,设有下面的一个SQLMAP脚本:

 

复制代码
<Select CommandName="GetRemindsBywhere" CommandType="Text" Method="" Description="查询提醒记录根据条件" ResultClass="DataSet"><![CDATA[select a.guid,a.remindttile,a.remindcontent,a.reminddate,
case when a.isread = 0 then '未处理' else '已处理' end isread,b.customername,c.modelname,b.guid userid
from WFT_RemindRecord a  
left join WFT_Customer b on a.customerid = b.guid 
left join Tb_Common_ModelInfo c on a.remindtypeid = c.modelid
where 1=1  and   #%tiaojian%# 
]]></Select>
    
</CommandClass>

复制代码

 

 

使用“替换参数”,仅需要在参数名外面包一个 #%..%# 即可,不需要指定参数的类型,因为“替换”本身就是针对字符串的替换,例如下面的方式是不正确的:
where 1=1  and   #%tiaojian:String%#

只需要这样:
where 1=1  and   #%tiaojian%#

2,SQLMAP DAL代码:
使用代码生成工具,上面的SQLMAP脚本将生成下面的DAL代码:

复制代码
 /// <summary>
    
/// 查询提醒记录根据条件
    
/// </summary>
    
/// <returns></returns>
    public DataSet GetRemindsBywhere(string tiaojian  ) 
    { 
            
//获取命令信息
            CommandInfo cmdInfo=Mapper.GetCommandInfo("GetRemindsBywhere");
            
//执行参数替换
            cmdInfo.SetParameterValue("tiaojian", tiaojian, enumParamType.ReplacedText);
            
//执行查询
            return CurrentDataBase.ExecuteDataSet(CurrentDataBase.ConnectionString, cmdInfo.CommandType, cmdInfo.CommandText ,null);
        
//
    }//End Function

复制代码

 

 

从代码可以看出,SQLMAP脚本在红的参数名“tiaojian” 映射成了方法的参数 String tiaojian,而设置参数的方式变成了下面的方式:
cmdInfo.SetParameterValue("tiaojian", tiaojian, enumParamType.ReplacedText);

关键之处就是多了一个重载参数:enumParamType.ReplacedText


使用“替换参数”,在参数数量和参数类型不固定的情况下可以非常灵活的使用,反之则不推荐,尽量使用明确类型的参数,避免带来“SQL注入”的安全隐患。

 

 

 

posted on   深蓝医生  阅读(3207)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

< 2010年11月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11
点击右上角即可分享
微信分享提示