我使用下一个:
/// <summary>
/// Escape SQL.
/// </summary>
/// <param name="value">Value</param>
/// <param name="emptyToNull">Convert EMPTY to NULL?</param>
/// <param name="test">Default: "=". Values: = | != | <> | < | > | LIKE</param>
/// <returns>String SQL</returns>
public static string EscapeSql(object value, bool emptyToNull = true, string test = "=")
{
// Test
if (string.IsNullOrWhiteSpace(test))
{
test = "=";
}
else
{
test = test.Trim().ToUpper();
if (test == "!=")
test = "<>";
}
// Null
if (value == null)
return EscapeSql_NullTest(test);
// DateTime
if (value is DateTime)
return string.Concat(test, " '", ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"), "'");
// Number
if ((value is decimal) || (value is int) || (value is Int16) || (value is Int32) || (value is Int64))
return string.Concat(test, " ", value.ToString());
// Boolean
if (value is bool)
return string.Concat(test, " ", (bool)value ? 1 : 0);
// String
string s = value.ToString();
if (emptyToNull && string.IsNullOrEmpty(s))
return EscapeSql_NullTest(test);
// Replace ' -> ''
return string.Concat(test, " '", string.Join("''", s.Split('\'')), "'");
}
private static string EscapeSql_NullTest(string test)
{
return (test == "<>") ? "IS NOT NULL" : "IS NULL";
}
使用SQL参数与sqlcommand – 2012-07-17 17:57:22