清理SQL数据

Lor*_*tel 10 c# sql security

Google提出了各种关于清理Web访问查询的讨论,但我找不到任何解决我关注的问题:

在ac#程序中清理用户输入数据.这必须通过可逆转换完成,而不是通过删除.作为问题的一个简单例子,我不想破坏爱尔兰名字.

什么是最好的方法,是否有任何库函数可以做到这一点?

roo*_*ook 9

这取决于您使用的SQL数据库.例如,如果你想在MySQL中使用单引号文字,你需要使用反斜杠,Dangerous:'和一个转义的转义字符文字:\'.对于MS-SQL来说,事情是完全不同的,危险:' 逃脱:''.以这种方式转义数据时没有删除任何内容,它是一种表示控件字符(如文字形式的引号)的方法.

以下是从文档中获取MS-SQL和C#的参数化查询的示例:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于MySQL,我不知道您可以使用的参数化查询库.你应该使用mysql_real_escape_string()或者你可以使用这个函数:

public static string MySqlEscape(this string usString)
{
    if (usString == null)
    {
        return null;
    }
    // SQL Encoding for MySQL Recommended here:
    // http://au.php.net/manual/en/function.mysql-real-escape-string.php
    // it escapes \r, \n, \x00, \x1a, baskslash, single quotes, and double quotes
    return Regex.Replace(usString, @"[\r\n\x00\x1a\\'""]", @"\$0");
}
Run Code Online (Sandbox Code Playgroud)