SQL参数化查询自动生成SqlParameter列表
string sql = @"INSERT INTO stu VALUES (@id,@name) ";
参数化查询是经常用到的,它可以有效防止SQL注入。但是需要手动去匹配参数@id,@name。数据量大时很繁琐,下面是自动填充SqlParameter列表的实现。
支持泛型,Object和ExpandoObject动态类型
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Dynamic;
namespace Comm
{
/// <summary>
/// 作者:徐晓硕
/// 邮箱:xuxiaoshuo@fang.com
/// 版本:v1.0.0
/// </summary>
public class GetSqlParameters
{
/// <summary>
/// 过滤参数的规则
/// </summary>
private static Regex reg = new Regex(@"@\S{1,}?(,|\s|;|--|\)|$)"); private static char[] filterChars = new char[] { ' ', ',', ';', '-',')' }; /// <summary>
/// 根据sql语句和实体对象自动生成参数化查询SqlParameter列表
/// </summary>
/// <typeparam name="T">实体对象类型</typeparam>
/// <param name="sqlStr">sql语句</param>
/// <param name="obj">实体对象</param>
/// <returns>SqlParameter列表</returns>
public static List<SqlParameter> From<T>(String sqlStr, T obj)
{
List<SqlParameter> parameters = new List<SqlParameter>(); List<string> listStr = new List<string>();
Match mymatch = reg.Match(sqlStr);
while (mymatch.Success)
{
listStr.Add(mymatch.Value.TrimEnd(filterChars).TrimStart('@'));
mymatch = mymatch.NextMatch();
}
Type t = typeof(T); PropertyInfo[] pinfo = t.GetProperties(); foreach (var item in listStr)
{
for (int i = ; i < pinfo.Length; i++)
{
if (item.Equals(pinfo[i].Name, StringComparison.OrdinalIgnoreCase))
{
parameters.Add(new SqlParameter() { ParameterName = "@" + item, Value = pinfo[i].GetValue(obj, null) });
break;
}
else
{
if (i == pinfo.Length - )
{
throw new Exception("查询参数@" + item + "在类型" + t.ToString() + "中未找到赋值属性");
}
}
}
} return parameters;
}
/// <summary>
/// 根据sql语句和实体对象自动生成参数化查询SqlParameter列表
/// </summary>
/// <param name="sqlStr">sql语句</param>
/// <param name="obj">实体对象</param>
/// <returns>SqlParameter列表</returns>
public static List<SqlParameter> From(String sqlStr, object obj)
{
List<SqlParameter> parameters = new List<SqlParameter>(); List<string> listStr = new List<string>();
Match mymatch = reg.Match(sqlStr);
while (mymatch.Success)
{
listStr.Add(mymatch.Value.TrimEnd(filterChars).TrimStart('@'));
mymatch = mymatch.NextMatch();
}
Type t = obj.GetType(); PropertyInfo[] pinfo = t.GetProperties(); foreach (var item in listStr)
{
for (int i = ; i < pinfo.Length; i++)
{
if (item.Equals(pinfo[i].Name, StringComparison.OrdinalIgnoreCase))
{
parameters.Add(new SqlParameter() { ParameterName = "@" + item, Value = pinfo[i].GetValue(obj, null) });
break;
}
else
{
if (i == pinfo.Length - )
{
throw new Exception("查询参数@" + item + "在类型" + t.ToString() + "中未找到赋值属性");
}
}
}
} return parameters;
} /// <summary>
/// 根据sql语句和ExpandoObject对象自动生成参数化查询SqlParameter列表
/// </summary>
/// <param name="sqlStr">sql语句</param>
/// <param name="obj">ExpandoObject对象</param>
/// <returns>SqlParameter列表</returns>
public static List<SqlParameter> From(String sqlStr, ExpandoObject obj)
{
List<SqlParameter> parameters = new List<SqlParameter>(); List<string> listStr = new List<string>();
Match mymatch = reg.Match(sqlStr);
while (mymatch.Success)
{
listStr.Add(mymatch.Value.TrimEnd(filterChars).TrimStart('@'));
mymatch = mymatch.NextMatch();
}
IDictionary<String, Object> dic=(IDictionary<String, Object>)obj; foreach (var item in listStr)
{
int reachCount = ;
foreach (var property in dic)
{
if (item.Equals(property.Key, StringComparison.OrdinalIgnoreCase))
{
parameters.Add(new SqlParameter() { ParameterName = "@" + item, Value = property.Value });
break;
}
else
{
if (reachCount == dic.Count-)
{
throw new Exception("查询参数@" + item + "在类型ExpandoObject中未找到赋值属性");
}
}
reachCount++;
}
}
return parameters;
}
}
}
Demo代码
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using Framework.Data;
using System.Data;
using System.Data.SqlClient;
using System.Dynamic;
using Comm;
namespace 数据层
{
class Program
{
static void Main(string[] args)
{ string sql = @"INSERT INTO stu VALUES (@id,@name) "; dynamic wherePart = new ExpandoObject();
wherePart.ID = "";
wherePart.Name = "Test";
List<SqlParameter> listPar2 = GetSqlParameters.From(sql, wherePart);
foreach (var item in listPar2)
{
Console.WriteLine(item.ParameterName + ":" + item.Value);
} Console.ReadKey();
}
}
}
转载:http://blog.csdn.net/xxs77ch/article/details/51513722
SQL参数化查询自动生成SqlParameter列表的更多相关文章
- SQL Server镜像自动生成脚本
SQL Server镜像自动生成脚本 镜像的搭建非常繁琐,花了一点时间写了这个脚本,方便大家搭建镜像 执行完这个镜像脚本之后,最好在每台机器都绑定一下hosts文件,不然的话,镜像可能会不work 1 ...
- SQL参数化查询
参数化查询(Parameterized Query 或 Parameterized Statement)是指在设计与数据库链接并访问数据时,在需要填入数值或数据的地方,使用参数 (Parameter) ...
- SQL 参数化查询 应用于 Like
在sql 进行参数化查询的时候,使用like 语句和参数的时候,错误的写法: Participant like '%@Participant%' ,这样在数据库为解析为 '%'participant ...
- sql 参数化查询问题
一.正确案例 string name=“梅”; string sql="select * from test where Name like @Name"; //包含 梅Sql ...
- sql 参数化查询
在初次接触sql时,笔者使用的是通过字符串拼接的方法来进行sql查询,但这种方法有很多弊端 其中最为明显的便是导致了sql注入. 通过特殊字符的书写,可以使得原本正常的语句在sql数据库里可编译, ...
- SQL参数化查询--最有效可预防SQL注入攻击的防御方式
参数化查询(Parameterized Query 或 Parameterized Statement)是访问数据库时,在需要填入数值或数据的地方,使用参数 (Parameter) 来给值. 在使用参 ...
- SQL参数化查询的问题
最近碰到个问题, SQL语句中的 "... like '%@strKeyword%'"这样写查不出结果, 非的写成 "... like '%" + strKey ...
- mybatis的sql参数化查询
我们使用jdbc操作数据库的时候,都习惯性地使用参数化的sql与数据库交互.因为参数化的sql有两大有点,其一,防止sql注入:其二,提高sql的执行性能(同一个connection共用一个的sql编 ...
- 查询自动生成Guid列
--newid()可以在查询的时候自动生成Guid列 ' ordey by Random --创建对应的列 用 uniqueidentifier 类型 IF NOT EXISTS ( SELECT * ...
随机推荐
- 记录yii2-imagine几个常用方法
记录yii2-imagine几个常用方法: //压缩 Image::thumbnail('@webroot/img/test-image.jpg', 120, 120)->save(Yii::g ...
- RDCMan
Remote Desktop Connection Manager (RDCMan) 是微软Windows Live体验团队的主要开发者 Julian Burger开发的一个远程桌面管理工具.简称为R ...
- 1、SQL Server自动化运维 - 备份(一)业务数据库
为了能够恢复数据,数据库运维基础就是备份,备份自动化也是运维自动化首要进行的. 笔者的备份自动化,通过配置表快速配置为前提,同时记录备份过程,尽可能的减少人工操作.首先将SQL Server备份按用途 ...
- C# Async, Await and using statements
Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area Support ...
- MVC路由配置例
public static void RegisterRoutes(RouteCollection routes) { string suffix = string.Empty; routes.Ign ...
- PYTHON 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
def a3(arg): ret = [ ] for i in range(len(arg)): if i % 2 == 1: ret.append(arg[i]) else: pass return ...
- Python全栈开发【re正则模块】
re正则模块 本节内容: 正则介绍 元字符及元字符集 元字符转义符 re模块下的常用方法 正则介绍(re) 正则表达式(或 RE)是一种小型的.高度专业化的编程语言. 在Python中,它内嵌在Pyt ...
- JQ倒计时天时分秒
<div id="times_wrap" class="time_num"> 距离现在时间: <div class="time_w& ...
- component
在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的Java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类 ...
- View手动切换焦点注意事项
这几天一直在解决一个焦点切换的问题,由于是直接用另外一家公司的代码,没有细看.当应用到测试那边,发现了这个问题,而且真机调试有些问题,不能单步调试,后来是看日志才发现这个问题. ViewA包含几个可以 ...