插入DB带参数的SQL注入安全吗? [英] Inserting into DB with parameters safe from SQL injection?

查看:100
本文介绍了插入DB带参数的SQL注入安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一些关于SQL注入和我想确保我的code是可以说安全从中,我打算用正则表达式验证器来检查用户输入,但另一篇文章在这里只建议使用参数化querys,以及我使用他们,但我想确保我的code是安全的,是吗?

I been reading a bit about SQL injection and I want to be sure my code is lets say "safe" from it, I was planning on using RegExp validators to check the user input but another post in here suggested only using parametrized querys, well I'm using them but I want to be sure my code is safe, is it?

        using ( SqlConnection dataConnection = new SqlConnection(myConnectionString) )
        {
            using ( SqlCommand dataCommand = dataConnection.CreateCommand() )
            {
                dataCommand.CommandText = "INSERT INTO Lines (Name, CreationTime) " +
                    "VALUES (@LineName, @CurrentDateTime)";

                dataCommand.Parameters.AddWithValue("@LineName", TextBox2.Text);
                dataCommand.Parameters.AddWithValue("@CurrentDateTime", DateTime.Now.ToString());
                dataConnection.Open();
                //do other DB stuff

我砍的最后一部分,使短后,剩下的只是想和捕获异常和关闭数据库连接,以及如何插入成功提供用户反馈。

I chop the last part to make the post shorter, the rest is just trying and catching exceptions and closing db connection as well as providing user feedback on inserting successful.

推荐答案

您code是好的,它是从注入,因为这些值作为参数不是字符串传递保护。但是,如果你正在写这种类型的数据访问自己,你有没有考虑创建<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx\">SqlParameter对象和显式设置的类型,大小等,并添加参数的命令? AddWithValue会工作得很好,但SQL Server必须确定的类型,一点点,但不必要的开销。

Your code is fine, it is protected from injection because the values are passed as parameters not string literals. However, if you are writing this type of data access yourself, have you considered creating SqlParameter objects and explicitly setting the type, size etc, and adding the parameters to the command? AddWithValue will work just fine, but SQL Server will have to determine the type, a little, but unnecessary overhead.

这篇关于插入DB带参数的SQL注入安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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