Solving the problem of SQLinjection

这一生的挚爱 提交于 2019-12-24 04:53:08

问题


For my login control I'm using parameters in an SQL statement. Trouble is if people use SQLinjection, I'm afraid they'll be able to get in too.

I have two textboxes and the values are passed on to an SQL statement, this checks whether the values are found in the DB.

Is there a way to make sure this isn't possible? I know in PHP you need to use something infront of the textboxes.

Thanks for your time!


回答1:


Use parameters in your queries:

// C#
SqlCommand cmd = new SqlCommand("UPDATE Products SET description = @Description WHERE id = @ID");
cmd.Parameters.AddWithValue("@Description", "something");
cmd.Parameters.AddWithValue("@ID", 123);

And the equivalent in VB.net:

// VB.net
Dim cmd As New SqlCommand("UPDATE Products SET description = @Description WHERE id = @ID")
cmd.Parameters.AddWithValue("@Description", "something")
cmd.Parameters.AddWithValue("@ID", 123)



回答2:


Yes, you should use SqlParameter.




回答3:


Parameterised queries are recommended

See example below

Private Sub DisplayPersonData(ByVal first_name As String, _
    ByVal last_name As String)
    ' Open the connection.
    connUsers.Open()

    ' Make a Command for this connection
    ' and this transaction.
    Dim cmd As New OleDb.OleDbCommand( _
        "SELECT * FROM People WHERE FirstName=? AND " & _
            "LastName=?", _
        connUsers)

    ' Create parameters for the query.
    cmd.Parameters.Add(New _
        OleDb.OleDbParameter("FirstName", first_name))
    cmd.Parameters.Add(New OleDb.OleDbParameter("LastName", _
        last_name))

    ' Execute the query.
    Dim db_reader As OleDbDataReader = _
        cmd.ExecuteReader(CommandBehavior.SingleRow)

    ' Display the results.
    If db_reader.HasRows Then
        db_reader.Read()
        txtFirstName.Text = _
            db_reader.Item("FirstName").ToString
        txtLastName.Text = _
            db_reader.Item("LastName").ToString
        txtStreet.Text = db_reader.Item("Street").ToString
        txtCity.Text = db_reader.Item("City").ToString
        txtState.Text = db_reader.Item("State").ToString
        txtZip.Text = db_reader.Item("Zip").ToString
    Else
        For Each ctl As Control In Me.Controls
            If TypeOf ctl Is TextBox Then ctl.Text = ""
        Next ctl
    End If

    ' Close the connection.
    connUsers.Close()
End Sub



回答4:


Use Stored Procedures and a database abstraction layer (ORM)




回答5:


If you have the appropriate server-side permissions, you can create stored procedures to accept the parameters rather than assigning an update statement to the command object. SPs also provide better performance than dynamic DML statements.



来源:https://stackoverflow.com/questions/6043389/solving-the-problem-of-sqlinjection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!