这个SQL查询有什么问题?

时间:2011-02-08 06:53:57

标签: .net vb.net sql-server-2005 tsql ado.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Literal1.Text = Request.QueryString("Pno")
    On Error Resume Next
    Dim SQLData As New System.Data.SqlClient.SqlConnection("workstation id=ws.example.com;packet size=4096;user id=some-user;pwd=some-password;data source=mssql.example.com;persist security info=False;initial catalog=some-db")
    Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM a1_ticket WHERE PNR_no ='" & Literal1.Text & "'", SQLData)
    SQLData.Open()
    Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
    If dtrReader.HasRows Then
        While dtrReader.Read()
            Literal2.Text = dtrReader("bus_type")
            Literal3.Text = dtrReader("dep_time")
            Literal4.Text = dtrReader("PRN")
            Literal5.Text = dtrReader("fro_m")
            Literal6.Text = dtrReader("seat_opt")
            Literal7.Text = dtrReader("Ticket_no")
            Literal8.Text = dtrReader("t_o")
            Literal9.Text = dtrReader("taxes")
            Literal10.Text = dtrReader("Travels")
            Literal11.Text = dtrReader("journey_date")
            Literal12.Text = dtrReader("net_pay")
            Literal13.Text = dtrReader("name")
            Literal14.Text = dtrReader("seat_opt")
            Literal15.Text = dtrReader("sel_seat")
            Literal16.Text = dtrReader("bd_point")
        End While
    Else
    End If
    Dim cmd As New System.Data.SqlClient.SqlCommand("SELECT * FROM a1_vendors WHERE UserId ='" & Request.QueryString("tid") & "'", SQLData)
    cmd.ExecuteScalar()
    Literal17.Text = dtrReader("travels")
    Literal18.Text = dtrReader("Contactno")
    SQLData.Close()
    dtrReader.Close()
    SQLData.Close()
End Sub

2 个答案:

答案 0 :(得分:6)

此查询有什么问题?它正在乞求SQL注入攻击。

请参阅:

Dim cmd As New SqlCommand(
   "SELECT * FROM a1_vendors WHERE UserId ='" & 
   Request.QueryString("tid") & "'", SQLData)

如果Request.QueryString("tid")包含值“'' GO DROP TABLE a1_vendors GO SELEC ''

,该怎么办?

突然你的命令变成了“SELECT * FROM a1_vendors WHERE UserId = '' GO DROP TABLE a1_vendors GO SELECT ''

答案 1 :(得分:3)

期待你的意思是第二个,你SELECT *但是ExecuteScalar; ExecuteScalar只返回一个值(作为结果) - 并且它不会更新阅读器,因此Literal17 / Literal18正在从无处获取其值。

按照现有模式,它应该是:

' caveat: this is **not** intended as a perfect example; this intentionally
' uses the same pattern as the question; see below for notes
dtrReader = cmd.ExecuteReader()
If dtrReader.Read()
    Literal17.Text = dtrReader("travels")
    Literal18.Text = dtrReader("Contactno")
End If

更重要的是,虽然

  • 没有分离;来自连接字符串管理,帐户凭据(感谢那些,顺便说一句),数据访问和UI在Page_Load事件中处理,本身是牙齿咬牙切齿的原因< / LI>
  • 易受SQL注入
  • no using(或VB等价物)以确保您具有确定性清理,而不是等待垃圾收集(在不可避免的例外事件中)