SafeSQL.cs
跳至導覽
跳至搜尋
用途
- 自組SQL命令字串時,避免帶入的參數導致SQL資料隱碼。
- 方便傳入Parameter或SqlParameter用的參數。
程式碼
using System; using System.Data; using System.Data.SqlClient; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; /// <summary> /// Class SafeSQL /// 手動組合SQL的字串時, 避免發生SQL資料隱碼 /// </summary> public class SafeSQL { public static string Quote(string strData) { return string.Format("'{0}'", strData.Replace("'", "''")); } public static string QuoteLike(string strData) { return string.Format("'%{0}%'", strData.Replace("'", "''")); } public static string QuoteLikeRight(string strData) { return string.Format("'{0}%'", strData.Replace("'", "''")); } public static string QuoteLikeLeft(string strData) { return string.Format("'%{0}'", strData.Replace("'", "''")); } public static string NoQuote(string strData) { return strData.Replace("'", "''"); } #region Parameter public static Parameter CreateSessionParameter(string paramName, TypeCode type, string sessionField) { Parameter parameter = new Parameter(paramName, type); object objValue = HttpContext.Current.Session[sessionField]; if (objValue == null) { parameter.DefaultValue = ""; } else { parameter.DefaultValue = objValue.ToString(); } return parameter; } public static Parameter CreateControlParameter(string paramName, TypeCode type, string idControl, string propertyName, Control control) { Parameter parameter = new Parameter(paramName, type); Control component = control.FindControl(idControl); object objValue = DataBinder.Eval(component, propertyName); if (objValue == null) { parameter.DefaultValue = ""; } else { parameter.DefaultValue = objValue.ToString(); } return parameter; } #endregion Parameter #region SqlParameter public static SqlParameter CreateInputParam(string paramName, SqlDbType dbType, object objValue) { SqlParameter parameter = new SqlParameter(paramName, dbType); if (objValue == null) { parameter.IsNullable = true; parameter.Value = DBNull.Value; } else { parameter.Value = objValue; } return parameter; } public static SqlParameter CreateInputParam(string paramName, SqlDbType dbType, int size, object objValue) { SqlParameter parameter = new SqlParameter(paramName, dbType, size); if (objValue == null) { parameter.IsNullable = true; parameter.Value = DBNull.Value; } else { parameter.Value = objValue; } return parameter; } public static SqlParameter CreateOutputParam(string paramName, SqlDbType dbType, int size) { SqlParameter parameter = new SqlParameter(paramName, dbType); parameter.Direction = ParameterDirection.Output; parameter.Size = size; return parameter; } #endregion SqlParameter }