防Sql注入的两个简单解决办法
第一种方法:
1.所有传入的Sql参数统统都用SqlParameter来写.
第二种方法
1.对所有要传入的参数做Sql关键字符过滤.
用法:
string strSql = "select * from UserInfo where UID = {0}";
strSql = FormatSql(strSql,tbUID.Text);
/// <summary>
/// Sql语句过滤处理类
/// </summary>
public static class SqlFilter
{
/// <summary>
/// 过滤Sql注入的字符
/// </summary>
/// <param name="sqlCondition">要过滤的Sql数据 </param>
/// <returns> </returns>
public static string FilterInjection(string sqlCondition)
{
if (sqlCondition.Trim() != string.Empty)
sqlCondition = sqlCondition.Trim();
sqlCondition = sqlCondition.Replace("''", "");
sqlCondition = sqlCondition.Replace("'", "''");
sqlCondition = sqlCondition.Replace("_", @"\_");
sqlCondition = sqlCondition.Replace("%", @"\%");
return sqlCondition;
}
public static string AddEsCape(string strSql, string sqlCondition)
{
string m_ReturnSql = string.Empty;
if (sqlCondition.Contains(@"\%") || sqlCondition.Contains(@"\_"))
{
m_ReturnSql = string.Format(strSql, sqlCondition) + @" escape '\' ";
}
else
{
m_ReturnSql = string.Format(strSql, sqlCondition);
}
return m_ReturnSql;
}
public static string FormatSql(string strSql, string sqlCondition)
{
string m_Condition = FilterInjection(sqlCondition);
if (string.IsNullOrEmpty(m_Condition))
{
return string.Empty;
}
else
{
return AddEsCape(strSql, m_Condition);
}
}
}
1.所有传入的Sql参数统统都用SqlParameter来写.
第二种方法
1.对所有要传入的参数做Sql关键字符过滤.
用法:
string strSql = "select * from UserInfo where UID = {0}";
strSql = FormatSql(strSql,tbUID.Text);
/// <summary>
/// Sql语句过滤处理类
/// </summary>
public static class SqlFilter
{
/// <summary>
/// 过滤Sql注入的字符
/// </summary>
/// <param name="sqlCondition">要过滤的Sql数据 </param>
/// <returns> </returns>
public static string FilterInjection(string sqlCondition)
{
if (sqlCondition.Trim() != string.Empty)
sqlCondition = sqlCondition.Trim();
sqlCondition = sqlCondition.Replace("''", "");
sqlCondition = sqlCondition.Replace("'", "''");
sqlCondition = sqlCondition.Replace("_", @"\_");
sqlCondition = sqlCondition.Replace("%", @"\%");
return sqlCondition;
}
public static string AddEsCape(string strSql, string sqlCondition)
{
string m_ReturnSql = string.Empty;
if (sqlCondition.Contains(@"\%") || sqlCondition.Contains(@"\_"))
{
m_ReturnSql = string.Format(strSql, sqlCondition) + @" escape '\' ";
}
else
{
m_ReturnSql = string.Format(strSql, sqlCondition);
}
return m_ReturnSql;
}
public static string FormatSql(string strSql, string sqlCondition)
{
string m_Condition = FilterInjection(sqlCondition);
if (string.IsNullOrEmpty(m_Condition))
{
return string.Empty;
}
else
{
return AddEsCape(strSql, m_Condition);
}
}
}