什么是防止 SQL 注入的好方法? [英] What are good ways to prevent SQL injection?

查看:24
本文介绍了什么是防止 SQL 注入的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为我的 OJT 公司编写一个应用程序管理系统.前端将使用 C# 完成,后端将使用 SQL.

I have to program an application management system for my OJT company. The front end will be done in C# and the back end in SQL.

现在我从来没有做过这个范围的项目;在学校,我们只有关于 SQL 的基本课程.不知何故,我们的老师完全没有讨论 SQL 注入,这是我现在在网上阅读有关它才接触到的东西.

Now I have never done a project of this scope before; in school we had only basic lessons about SQL. Somehow our teacher completely failed to discuss SQL injections, something which I have only now come in contact with by reading about it on the net.

无论如何,我的问题是:如何防止 C# 中的 SQL 注入?我模糊地认为可以通过正确屏蔽应用程序的文本字段来完成,以便它只接受指定格式的输入.例如:电子邮件文本框的格式应为example@examplecompany.tld".这种方法是否足够?或者 .NET 是否具有处理此类内容的预定义方法?我可以对文本框应用过滤器,使其只接受电子邮件地址格式或名称文本框,从而不接受特殊字符吗?

So anyway my question is: how do you prevent SQL injections in C#? I vaguely think that it can be done by properly masking the text fields of the application so that it only accepts input in a specified format. For example: an e-mail textbox should be of the format "example@examplecompany.tld". Would this approach be sufficient? Or does .NET have pre-defined methods that handle stuff like this? Can I apply a filter to a textbox so it only accepts email-address format or a name textbox so it doesn't accept special chars?

推荐答案

通过使用 SqlCommand 及其 子参数集合所有检查sql注入的痛苦都从你身上带走,将由这些类来处理.

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

这里是一个例子,取自上面的一篇文章:

Here is an example, taken from one of the articles above:

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

这篇关于什么是防止 SQL 注入的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆