SQL

为什么我们总是喜欢在SQL语句中使用参数?

发布于 2021-05-10 20:50:24

我对使用数据库非常陌生。现在我可以写SELECTUPDATEDELETE,和INSERT命令。但是我看过很多我们喜欢写的论坛:

SELECT empSalary from employee where salary = @salary

…代替:

SELECT empSalary from employee where salary = txtSalary.Text

为什么我们总是喜欢使用参数,我将如何使用它们?

我想知道第一种方法的用途和好处。我什至听说过SQL注入,但是我不太了解。我什至不知道SQL注入是否与我的问题有关。

关注者
0
被浏览
203
1 个回答
  • 面试哥
    面试哥 2021-05-10
    为面试而生,有面试问题,就找面试哥。

    当数据库与程序界面(例如桌面程序或网站)结合使用时,使用参数有助于防止 SQL注入攻击

    在您的示例中,用户可以通过编写中的语句直接在数据库上运行SQL代码txtSalary

    例如,如果他们要编写0 OR 1=1,则执行的SQL将是

     SELECT empSalary from employee where salary = 0 or 1=1
    

    从而所有empSalaries都将被退回。

    此外,用户可能会对您的数据库执行更差的命令,包括删除以下命令0; Drop Table employee

    SELECT empSalary from employee where salary = 0; Drop Table employee
    

    employee然后将删除该表。


    就您而言,您似乎正在使用.NET。使用参数非常简单:

        string sql = "SELECT empSalary from employee where salary = @salary";
    
        using (SqlConnection connection = new SqlConnection(/* connection info */))
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            var salaryParam = new SqlParameter("salary", SqlDbType.Money);
            salaryParam.Value = txtMoney.Text;
    
            command.Parameters.Add(salaryParam);
            var results = command.ExecuteReader();
        }
    
    
    
    
        Dim sql As String = "SELECT empSalary from employee where salary = @salary"
        Using connection As New SqlConnection("connectionString")
            Using command As New SqlCommand(sql, connection)
                Dim salaryParam = New SqlParameter("salary", SqlDbType.Money)
                salaryParam.Value = txtMoney.Text
    
                command.Parameters.Add(salaryParam)
    
                Dim results = command.ExecuteReader()
            End Using
        End Using
    

    编辑2016-4-25:

    根据George Stocker的评论,我将示例代码更改为not use
    AddWithValue。另外,通常建议您将IDisposables包装在using语句中。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看