System.InvalidOperationException:ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭

时间:2016-02-10 07:47:04

标签: vb.net ms-access executereader

我遇到的客户服务模块存在问题,该模块位于不同的解决方案中。我认为问题在于我调用或获取连接的方法

这是我的班级名为 DBConnForAccess

Imports System.Data.OleDb
Imports System.Data.Odbc

Public Class DBConnForAccess

Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction

Public Function DBConnect(ByVal filePath As String, pass As String)
    Try
        ' open Database

        'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
        Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
        '                          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"

        If Conn.State = ConnectionState.Closed Then
            Conn.Open()
        End If

        ' create transaction
        Trans = Conn.BeginTransaction
        Return "Ok"

    Catch ex As Exception
        Return ex.Message
    End Try

End Function

Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
    ' command Object
    Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)

    'add the parameters to the sql command
    Dim I As Integer
    For I = 0 To Obj.Length - 1
        CMD.Parameters.AddWithValue("@" & I, Obj(I))
    Next

    'execute the sql
    CMD.ExecuteNonQuery()
End Sub

Public Sub commit()
    Me.Trans.Commit()
    Me.Trans = Me.Conn.BeginTransaction
End Sub

Public Sub rollback()
    Me.Trans.Rollback()
    Me.Trans = Me.Conn.BeginTransaction
End Sub

Public Sub CloseDB()
    Me.Conn.Close()
    Me.Conn.Dispose()
    Me.Trans.Dispose()
End Sub

Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
    ' command Object
    Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)

    'add the parameters to the sql command
    Dim I As Integer
    For I = 0 To Obj.Length - 1
        CMD.Parameters.AddWithValue("@" & I, Obj(I))
    Next

    Dim R = CMD.ExecuteReader()
    'Do While R.Read

    'Loop
    Return R

End Function
End Class

以下是我用于获取数据

的Sub
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
 'connection string is in a text file with text at line 0 as "C:\BILLSERV\"

 Private Sub searchAccnt(ByVal SIN As String)
    'clear other fields
    Clear("Acct")
    Try
        AccntDetail.DBConnect("ConcessionairesAccnt")
        'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=@0", txtSIN.Text.Trim)
        Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=@0", SIN)

        RS.Read()
        If RS.Hasrows = 0 Then
            MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
            'txtAppNo.Focus()
            Exit Sub
        Else
            'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
            txtZoneNo.Text = RS.Item("Zone").ToString
            txtSeq.Text = RS.Item("SeqNo").ToString
            txtAccntName.Text = RS.Item("AccountName").ToString
            txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
                                   " " + RS.Item("BRGY").ToString
            txtMeterNo.Text = RS.Item("MeterNo").ToString
            txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)


            'Dim con = AccessAccnt.DBConnect(connection, "")
            'If con <> "Ok" Then
            '    MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
            'End If

            Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
            AccessAccnt.DBConnect(connection, "")
            Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=@1", txtSeq.Text)
            Acc.Read()
            txtLastReading.Text = Acc.Item("LastReading").ToString
            Acc.close()
            AccessAccnt.CloseDB()

        End If
        RS.Dispose()
        AccntDetail.CloseDB()

        dbCounter.DBConnect("ConcessionairesAccnt")
        Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
        result.read()
        If result.hasrows = 0 Then
            txtTrackingNo.Text = ctrDate() & "-" & "000001"
        Else
            txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
        End If
        dbCounter.CloseDB()

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

End Sub

此处抛出错误:

Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=@1", txtSeq.Text)

它说:

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.

Sub Works的其他部分很好,我在MSSQL Server数据库上获取数据的部分。问题在于访问数据 - 获取代码。

我尝试在另一个项目上使用代码(只是我获取访问数据的代码)我在其他解决方案上工作。但我在我的解决方案中的任何表单上复制并粘贴我的代码我一直给出错误。

我想也许我在某处关闭了连接,但这是我在整个项目中使用此代码的唯一实例。 (只是为了得到最后的阅读记录。)

数据库位于正确的位置(C:\ BILLSERV)

我尝试在SE上搜索它,但我可以看到有关可能忘记打开连接的建议。之前我使用过此代码,此代码适用于我的其他解决方案。我似乎无法在这个特定的项目中使用它。我想知道为什么......

我尝试使用此代码运行另一个项目,它运行正常。

在VB.net 2012上是否存在关于Access连接的错误,我已经使用此代码(DBConnForAccess类)大约一年了,这是我第一次遇到此错误。顺便说一句我使用Access 2003,因为这个数据库曾经是用于在VB6中创建的旧系统。

最后可能是因为解决方案来自另一台使用与我相同的VB.Net程序的计算机。因为我们在这里工作。希望对这些系统有更好了解的人可以提供帮助。提前谢谢。

修改

如果已建立连接,则应该存在一个应该出现的.ldb文件。 (我在另一个项目上测试了这个,并且一旦建立连接就会出现一个ldb文件,因为我们都知道ldb文件包含使用db文件的用户数据。)我试图重新运行系统而我是使用系统没有创建ldb文件。

另外,我想也许我在某处关闭了连接,但这是我在访问中打开连接的唯一实例,我在整个项目中使用了代码。 (只是为了得到最后的阅读记录。)

所以“There is already an open DataReader…” Reuse or Dispose DB Connections?的副本只是为了澄清

1 个答案:

答案 0 :(得分:0)

经过一周的调试和在网上阅读文章。 我们找到了错误的罪魁祸首。

似乎高级编译器设置中的目标CPU选项已更改为 AnuCPU

在检查了我们使用的其他应用项目后,我们注意到了这一点。

将其更改回 x86 可解决连接问题。

Target CPU settings

我想知道为什么这会影响与访问的连接。

现在一切正常。感谢您PlutonixSteve提出的所有建议,我们将对代码进行更改。