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

查看:164
本文介绍了有什么好的方法prevent 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#prevent SQL注入?我隐约觉得,它可以通过适当屏蔽应用程序的文本字段,以便它仅接受指定格式的输入来完成。例如:电子邮件文本的格式应为example@examplecompany.tld的。请问这种做法是否足够呢?还是.NET有pre定义的方法来处理这​​样的东西?我可以申请一个过滤器,一个文本框,因此只接受电子邮件地址格式或名称文本框,因此不接受特殊字符?

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?

推荐答案

通过使用<$c$c>SqlCommand和它的<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx\">child的检查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);
        }
    }
}

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

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