0

你能解释我为什么会收到这个错误吗?

ExecuteReader:连接属性尚未初始化

Protected Sub btnLogin_Click(ByVal sender As Object, 
               ByVal e As System.EventArgs) Handles btnLogin.Click
    Dim name = txtUserName.Text.Trim
    Dim Pass = txtPassword.Text.Trim

    Try

        Dim conn As SqlConnection
        conn = DataBaseFunc.OpenConnection()

        Dim sqlSt As String = "select * FROM AdminLog WHERE AdminName = '" & name & "' AND AdminPassword = '" & Pass & "'"
        Dim SelCmd As SqlCommand = New SqlCommand(sqlSt, conn)

        Dim RrecSet As SqlDataReader

        RrecSet = SelCmd.ExecuteReader()

        If RrecSet.Read() Then
            Session("Admin") = RrecSet("AdminName")
            Response.Redirect("~/AdminPages/AdminHome.aspx")
        Else
            lblMsg.Text = "<p>Rong Username or Password</p>"
            txtUserName.Text = ""
            txtPassword.Text = ""
            txtUserName.Focus()

        End If
    Catch ex As Exception
        lblMsg.Text = ex.Message
    End Try
End Sub

数据库函数

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualBasic


Public Class DataBaseFunc
    Public Shared Sub EnsureOpenConnection(ByRef conn As SqlConnection)
        Try
            If conn.State <> Data.ConnectionState.Open Then
                conn.Open()
            End If
        Catch ex As Exception
        End Try
    End Sub


    Public Shared Function OpenConnection() As SqlConnection
        Try
            Dim ConnString As String = "server =.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BloodDb.mdf;Integrated Security=True;User Instance=True"
            Dim conn As New SqlConnection(ConnString)
            If conn.State <> Data.ConnectionState.Open Then
                conn.Open()
            End If
            Return conn
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

End Class
4

1 回答 1

0

将您的代码更改DataBaseFunc为这样的内容,MsgBox可能会让您更好地理解错误。
Try/Catch 内部没有实际代码(喜欢MsgBox(ex.toString)println(ex.toString)没用。在您尝试此操作后,报告更多信息。

Public Class DataBaseFunc
        Public Shared Sub EnsureOpenConnection(ByRef conn As SqlConnection)
            Try
                If conn.State <> Data.ConnectionState.Open Then
                    conn.Open()
                End If
            Catch ex As Exception
               MsgBox(ex.ToString)
            End Try
        End Sub


        Public Shared Function OpenConnection() As SqlConnection
            Try
                Dim ConnString As String = "server =.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BloodDb.mdf;Integrated Security=True;User Instance=True"
                Dim conn As New SqlConnection(ConnString)
                If conn.State <> Data.ConnectionState.Open Then
                    conn.Open()
                End If
                Return conn
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End Function
于 2015-06-13T17:08:03.510 回答