在C#中进行SQL查询的最安全方法是什么?

时间:2018-09-12 15:39:39

标签: c# sql .net

我正在使用一个简单的脚本根据用户输入来查询数据库,我想知道是否有注入诸如.net参数化查询之类的机会?

1 个答案:

答案 0 :(得分:1)

通过使用SqlCommand及其子参数集,所有检查sql注入的麻烦都将被您解放,并且将由这些类处理。

下面是一个示例,摘自Here

 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);
        }
    }