sqldatareader上的对象引用设置为null

时间:2014-03-19 11:53:54

标签: sql vb.net

我遇到以下代码的问题,

 Protected Sub lnkEdit_Click(sender As Object, e As EventArgs)
    Dim dr As SqlDataReader
    Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnectionConnectionString").ToString())
    Dim command As New SqlCommand()





    Try

        Dim lnk As LinkButton = TryCast(sender, LinkButton)
        Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow)
        Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString()
        ViewState("username") = eid
        sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle, Pager, mailaddress, from employees1 where username='" & eid & "'"
        If connection.State <> ConnectionState.Open Then
            connection.Open()
        End If
        command = New SqlCommand(sqlQry, connection)

        dr = command.ExecuteReader()
        If dr.Read() Then

            lblFirstName.Text = Convert.ToString(dr("FirstName"))
            lblSurname.Text = Convert.ToString(dr("Surname"))
            lblDepartmentName.Text = Convert.ToString(dr("DepartmentName"))
            lblExtensionName.Text = Convert.ToString(dr("ExtesionName"))
            lbljobTitle.Text = Convert.ToString(dr("jobTitle"))
            txtPager.Text = Convert.ToString(dr("Pager"))
            txtEmail.Text = Convert.ToString(dr("mailaddress"))
            'lblFirstName.Text = dr("FirstName").ToString()
            'lblSurname.Text = dr("Surname").ToString()
            'lblDepartmentName.Text = dr("DepartmentName").ToString()
            'lblExtensionName.Text = dr("ExtensionName").ToString()
            'lbljobTitle.Text = dr("jobTitle").ToString()
            'txtPager.Text = dr("Pager").ToString()
            'txtEmail.Text = dr("mailaddress").ToString()
            'txtMobile.Text = dr("MobileNumber").ToString()
            'lblUserName.Text = dr("username").ToString()

        End If
        mpe2.Show()
    Catch
        Return
    Finally
        command.Dispose()
        dr.Close()
        connection.Close()
    End Try

End Sub 

我理解sqldatareader抛出了null异常。

我试过

  dim dr as new sqldatareader

指出它无法被访问为#34;朋友&#34;

希望有人可以提供帮助。

由于

2 个答案:

答案 0 :(得分:1)

你有一个空的捕获块,吞噬任何异常。您在Finally中假设dr不为空并尝试关闭它。我会做三件事:

  1. 添加更好的异常处理,以便您知道真正的问题是什么。
  2. 在Finally块中添加if Not (dr Is Nothing)
  3. 切换到使用参数而不是连接SQL字符串 - 真正的问题可能是错误的eid输入值,并且您很容易受到SQL注入攻击。

答案 1 :(得分:0)

首先查看查询的逗号数超出需要

"select FirstName, Surname, DepartmentName, ExtensionName, jobTitle, Pager, mailaddress------>,<---- from employees1 where username='" & eid & "'"

必须是

"select FirstName, Surname, DepartmentName, ExtensionName, jobTitle, Pager, mailaddress from employees1 where username='" & eid & "'"

在调试模式下(或者如果你无法获取文件上的日志)获取正在执行的查询并直接在db查询编辑器上测试并查看是否正常工作,然后在代码中使用它

可能会对try一段时间进行注释会在dr = command.ExecuteReader()上给你一个SqlException异常,但是你会在finally块中得到异常,因为所有代码都被跳过了。