StringBuilder--拼接Sql語句防Sql注入

一、首先須要填寫一個StringBuilder的擴展類sql

namespace Code.Common { /// <summary>
    /// 擴展StringBuilder方法 /// 防止Sql注入 /// </summary>
    public static class StringBuilderExtend { public static StringBuilder AppendFormatWithSafe(this StringBuilder a, string format, object arg0, StringBuilder where) { where.AppendFormat(format, ((string)arg0) .ToLower() .Replace("update", "") .Replace("delete", "") .Replace("select", "") .Replace("insert", "") .Replace("from", "") .Replace("or", "") .Replace("'", "") .Replace("@", "") .Trim() ); return where; } } }

二、講這個擴展方法寫成公有靜態的,而後 每次new StringBuilder 拼接Sql語句的時候就能夠調用。下面調用案例(用的petapoco的Page分頁列表)ui

public static Page<UserInfo> GetList(Page<UserInfo> model, int myUserId = 0, int currentPage = 1) { Page<UserInfo> u = new Page<UserInfo>(); using (DataAccess.Database db = new DataAccess.Database()) { StringBuilder sql = new StringBuilder().Append(" select * from UserInfo where 1=1"); if (model.Item != null) { if (!string.IsNullOrEmpty(model.Item.RealName)) { sql.AppendFormatWithSafe(" and RealName like '%{0}%'", model.Item.RealName, sql); } } if (!string.IsNullOrEmpty(model.orderby)) { sql.AppendFormat(" order by {0}", model.orderby); } u = db.Page<UserInfo>(currentPage, CodeConfig.ItemsPerPage, sql.ToString(), myUserId); } return u; }

總結:this

  這樣就不用擔憂用戶輸入查詢條件的是帶有特殊字符,如( @‘ ),能夠作到防止Sql注入。spa

相關文章
相關標籤/搜索