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 = 0; 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 - 1)  
                        {  
                            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 = 0; 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 - 1)  
                        {  
                            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 = 0;  
                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-1)  
                        {  
                            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 = "1";  
            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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM