using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
/// <summary>
/// 資料庫輔助類別
/// </summary>
public static class DBUtility
{
private static string[] strLikeLiter = { "%", "_" };
/// <summary>
/// 存儲過程參數為空字串以 DB Null 值替代
/// </summary>
/// <param name="objInput"></param>
/// <returns></returns>
public static object FormatProcString(object objInput)
{
if (objInput == null || Convert.IsDBNull(objInput))
{
return DBNull.Value;
}
else
{
string str = objInput as string;
if (str != null)
{
if (str.Trim().Length == 0)
{
return DBNull.Value;
}
return str.Trim();
}
}
return objInput;
}
/// <summary>
/// 若參數值為空字串以 DB Null 值替代
/// </summary>
/// <param name="objInput">參數值</param>
/// <returns>回傳參數值,若參數值為空字串回傳 DB Null</returns>
public static object FormatParameterString(object objInput)
{
if (objInput == null || Convert.IsDBNull(objInput))
{
return DBNull.Value;
}
else
{
string str = objInput as string;
if (str != null)
{
if (str.Trim().Length == 0)
{
return DBNull.Value;
}
return str.Trim().Replace("'", "''");
}
}
return objInput;
}
/// <summary>
/// 替換參數中單引號(用於自組SQL語法)
/// </summary>
/// <param name="inputString">參數值</param>
/// <returns>替換後的參數值</returns>
public static string FormatRequestString(string inputString)
{
if (inputString.IsEmpty())
{
return "";
}
else
{
return inputString.Trim().Replace("'", "''");
}
}
/// <summary>
/// 於Like 時使用跳脫字元,以避免使用者使用[%]或[_]
/// </summary>
/// <param name="obj">參數值</param>
/// <param name="strEscape">跳脫字元</param>
/// <returns>回傳參數值,若參數值為空字串回傳 DB Null</returns>
public static object FormatLikeEscape(object obj, string strEscape)
{
object objValue = FormatParameterString(obj);
if (!Convert.IsDBNull(objValue))
{
string strValue = objValue.ToString();// FormatRequestString(objValue.ToString());
strValue = strValue.Replace(strEscape, String.Format("{0}{0}", strEscape));
for (int i = 0, iLen = strLikeLiter.Length; i < iLen; i++)
{
strValue = strValue.Replace(strLikeLiter[i],
String.Format("{0}{1}", strEscape, strLikeLiter[i]));
}
return strValue;
}
else
{
throw new ArgumentNullException("使用Like查詢時,參數值不可為Null");
}
}
}