VB2013: I am getting the exception System.Data.OleDb.OleDbException (0x80004005): System resource exceeded. When I query an MS Access database.
Here is what I do in my code:
'Make the connection to connDB
Public connDB As OleDbConnection
connDB = New OleDbConnection
With connDB
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbFile & ";Persist Security Info=True;Jet OLEDB:Database Password=xxxxxx;"
.Open()
End With
'iterate through some 2500 obects. each object has a set of codes and we will get their description here
GetSysDefinitions (list of codes for an object)
'Close the connection to connDB;
Public Function GetSysDefinitions(sysCodes As List(Of String)) As String
Try
'check to see if the db is available
If connDB Is Nothing Then Return ""
'set up the SQL to get the System Codes and Definitions
Dim sCodes As String = "'" & String.Join("', '", sysCodes) & "'"
Dim sql As String = "SELECT * " & _
"FROM SYS_Codes " & _
"WHERE CODE IN(" & sCodes & ") ; "
Dim daLs As New OleDbDataAdapter(sql, connDB)
Dim dsLs As New DataSet
Dim dtLs As New DataTable
daLs.SelectCommand.CommandTimeout = 60 '60 seconds for the command to timeout
daLs.Fill(dsLs, "Sys") '<=== Exception here at some point
dtLs = dsLs.Tables(0)
'do something with records returned
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Function
This all works great. At some point however I get the exception System.Data.OleDb.OleDbException (0x80004005): System resource exceeded at the line daLs.Fill. I just am not sure why resources are being exceeded and what I need to do to avoid this exception. Seems like I make one connection and then use it to make many queries. Should work right?
Thanks Çöđěxěŕ and Andrew Morton. Dont remeber where I got the code snippet but have been using it for years. I guess the difference is this time Im using that routine in a large number of calls. here is my updated code which I tested and no exceptions:
Using daLs As New OleDbDataAdapter(sql, connDb)
Using dtLs As New DataTable
'fill in the DataTable
daLs.Fill(dtLs)
dtLs.TableName = "CoreSys"
'check for how many rows were returned
'parse out rows
End Using
End Using
Related
I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called 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
Here is the Sub I use to fetch Data:
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
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.
I'm hitting the error mentioned in the Title when attempting to connect to the database in the VB.net application I'm developing. I know it's not the listener or any service issue, as I'm able to connect to the same database, with the same credentials in a different application I developed (I ran that application after failing to connect with the one I'm developing, so it's not the Windows Event log).
Both use an Oracle.DataAccess.Client.OracleConnection to reference an existing ODBC connection. The connections are created and opened in slightly different ways so I figure it's something in my VB code that's causing the issue, but I can't for the life of me think of what it might be.
The non-functional code:
Public Function EstablishCon(ByVal odbc As String,
ByVal uname As String,
ByVal pass As String) As Oracle.DataAccess.Client.OracleConnection
'
Dim constr As String
Dim scon As Oracle.DataAccess.Client.OracleConnection = Nothing
Try
constr = "Data Source=" & odbc & ";User Id=" & uname & ";Password=" & pass & ";"
scon = New Oracle.DataAccess.Client.OracleConnection(constr)
scon.Open()
Catch ex As Exception
MsgBox("Encountered an error while creating the Oracle connection string and opening the connection. This will cause the application to be unable to access any data." _
& " As such the application will close following the closure of this error message." & Chr(10) & Chr(10) & "Error Details: " & ex.Message, vbOKOnly, _
"Critical Error: Failed to the Oracle Database")
scon.ConnectionString = Nothing
End Try
Return scon
End Function
Whereas my working code looks like:
Private Sub MainWin_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'
'Dim scmd As New SqlClient.SqlCommand
Dim QTxt As String = ""
Dim ConStr As String = "Data Source=existing ODBC connection name;User Id=user_name;Password=pass;"
Dim scon As New Oracle.DataAccess.Client.OracleConnection(ConStr)
Dim d As New DataStore
Dim scmd As New Oracle.DataAccess.Client.OracleCommand
Dim odr As Oracle.DataAccess.Client.OracleDataReader
'Setup the datatable in d
Try
d.DT.Columns.Add("App_Type")
d.DT.Columns("App_Type").DataType = GetType(String)
d.DT.Columns.Add("CPU_Seconds")
d.DT.Columns("CPU_Seconds").DataType = GetType(Double)
'd.DT.Columns.Add("Pct_Of_CPU")
'd.DT.Columns("Pct_Of_CPU").DataType = GetType(Double)
d.DT.Columns.Add("RunDate")
d.DT.Columns("RunDate").DataType = GetType(Date)
Catch ex As Exception
Me.Errors.Text = "Encountered an error setting up the data table that will receive the query data. Details: " & ex.Message
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.Status.Text = Now() & " - Building the SQL executor"
Me.Refresh()
'Build the query executor
Try
scmd.CommandType = CommandType.Text
scmd.Connection = scon
'Capture the query text
QTxt = 'Some text that makes a valid query
scmd.CommandText = QTxt
Catch ex As Exception
Me.Errors.Text = "An error occurred while building the SQL Executor. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.ProgBar.Step = 5
Me.ProgBar.PerformStep()
Me.Status.Text = Now() & " - Connecting to the database" & Chr(10) & Me.Status.Text
Me.Refresh()
Try
'Open the connection
scon.Open()
Catch ex As Exception
Me.Errors.Text = "An error occurred while opening the SQL connection. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon.Close()
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
'Some more stuff that's not relevant
End Sub
Sorry for the messy formatting, I spent 15 minutes trying to keep the two blocks of code separate, but StackOverflow just wasn't having it.
So the only real difference between the two is that one filled in the connection string when declaring the Connection variable, and the other does so later and in a separate function. The function aspect doesn't appear to factor as the error is thrown and caught inside the function. I
So the problem was how I was invoking the form that calls for the function. I had use .Show rather than .ShowDialog.
This resulted in the form variables (which hold the values that get passed in as odbc, uname, & pass) being cleared prior to hitting the Shown event (where the connection function is invoked).
I have a VB.Net desktop application that does three tasks. First, it inserts data into Table A, then Table B, and finally, it copies a file from one directory to another. I am using transactions for my database inserts. In the event that an error occurs in any of the three steps, I want to roll back the transaction. The problem is, when a specific scenario occurs, and I roll back the transaction, i get the following error:
This OleDbTransaction has completed; it is no longer usable.
This happens if both database inserts succeed but the file copy fails. I'm not sure if I've set up my transactions wrong or what. If anyone has any feedback, let me know. Oh and the database I'm using is Oracle 10g. Bellow is my code:
Private Sub insertNew(ByVal doc As someObject)
Dim conString As String
conString = "Provider=MSDAORA.1;" _
& "User ID=" & My.Settings.User & ";" _
& "Password=" & My.Settings.Password & ";" _
& "Data Source=" & My.Settings.DatabaseName & ";" _
& "Persist Security Info=False"
Dim insertString1 As String
Dim insertString2 As String
Dim transaction As OleDbTransaction
insertString1 = "INSERT INTO mySchema.myTable1(ID_DOC, ID_DOC_FORMAT) VALUES (?,?)"
insertString2 = "INSERT INTO mySchema.myTable2(LOCATION_ID, PK_DOCUMENT) VALUES (?,?)"
Dim conn As New OleDbConnection(conString)
Try
Dim nextValue As Integer
'this function is a database call to get next sequence from database
nextValue = readData()
Using conn
conn.Open()
transaction = conn.BeginTransaction()
Dim command1 As New OleDbCommand
Dim command2 As New OleDbCommand
Try
With command1
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString1
.Parameters.Add("#IdDoc", OleDbType.VarChar).Value = doc.IdDoc
.Parameters.Add("#IdDocFormat", OleDbType.VarChar).Value = doc.IdDocFormat
.ExecuteNonQuery()
End With
Catch exCMD1 As Exception
Throw New ApplicationException("unable to insert into table DM_DOCUMENTS (" & exCMD1.Message & ")")
End Try
Try
With command2
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString2
.Parameters.Add("#IndPyramid", OleDbType.VarChar).Value = doc.IndPyramid
.Parameters.Add("#LocationId", OleDbType.Integer).Value = doc.LocationId
.ExecuteNonQuery()
End With
Catch exCMD2 As Exception
Throw New ApplicationException("unable to insert into table DM_LOCATION_DOC_XREF (" & exCMD2.Message & ")")
End Try
If copyFiles(doc.IdDoc) = True Then
transaction.Commit()
'everything was a success, so commit
Else
'error copying file, so roll back.
' If the error originates from here, it will throw to the next catch, and that is where I get the described error
Throw New ApplicationException("unable to copy to New Path")
End If
End Using
Catch ex As Exception
If transaction IsNot Nothing Then
'error occurs here if it came from trying to copy files code block
transaction.Rollback()
End If
Throw
Finally
conn.Close()
conn.Dispose()
End Try
End Sub
Never mind. It was because I was trying to rollback the transaction outside of the correct Try Catch statement. After you exit the using statement, the db stuff gets disposed of and this will cause the error. I just redid my try catch statements and now it works fine.
If you check whether the connection associated to that transaction is null or not then you are done.
Only apply commit or rollback if the connection object of the transaction is not null
eg.
OleDBTransaction testTransaction = someOleDBConnection.BeginTransaction();
//your all transactional codes
if(testTransaction.Connection != null)
testTransaction.Rollback() OR testTransaction.Commit() //Based on your requirement
you can try the different Isolation Level of transaction.
transaction = conn.BeginTransaction(IsolationLevel.ReadUncommitted)
https://msdn.microsoft.com/en-us/library/system.data.isolationlevel(v=vs.110).aspx
So, i get the OleDBException "unspecified error" whenever the function below hits the dataAdapter.Fill(dataset) line.
I have tried adding dbcommand.connection.close() and dbcommand.connection.dispose() but neither fixed the problem.
I assume that this error would happen every time i try to connect with the DB but this is just the first function that does so in my code, so this is where the error is first occuring.
I have read online that MySQL will eventually clear out old connections after a while, if this is true, then i should just have to wait..but i dont want to keep waiting for nothing to happen.
Function GetOrders(ByVal _numberrecords As Long) As DataTable
Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
Dim dbConnection As OleDbConnection = New OleDbConnection(TaxConnStr)
Try
'Code to get orders in call status. Sort oldest to newest
' dbConnection.Open()
Dim queryString As String
queryString = "SELECT TOP " & _numberrecords & " Orders.Control_Number, Orders.State, Orders.County, Orders.Status, Orders.ZipCode, Orders.OrderNumber, Orders.Client, Orders.Department "
queryString += "FROM Orders "
queryString += "WHERE(((Orders.Status) = 'Tax Cert Call' Or (Orders.Status) = 'Online')) "
queryString += "ORDER BY Orders.Date_Received;"
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
'dbCommand.Connection.Close()
'dbCommand.Connection.Dispose()
'dbCommand.Dispose()
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
If dataSet.Tables(0).Rows.Count >= 1 Then
GetOrders = dataSet.Tables(0)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
myLogger.Log(ex.Message)
Finally
dbConnection.Close()
dbConnection.Dispose()
End Try
End Function
Found the problem. My Access Database was corrupted. I just remade the database and it all worked like gravy.
Im new to visual basic.. I would like to ask on how to fixed the problem "Could not find installable ISAM.". I used Visual Basic as programming language. I used MS access as the database. My program is to fetch data from access. This would be my code.
Imports System.Data.OleDb
Module Main
Dim mDataPath As String
Sub Main()
GetPupils()
Console.ReadLine()
End Sub
Private Function GetConnection() As OleDb.OleDbConnection
'return a new connection to the database5
Return New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Database Password=oNer00FooR3n0 " & "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb")
End Function
Public Function GetPupils() As DataSet
Dim conn As OleDb.OleDbConnection = GetConnection()
Try
Dim ds As New DataSet 'temporary storage
Dim sql As String = "select * from SESSIONS" 'query
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, conn) 'connection
Try
da.Fill(ds, "SESSIONS") 'fetch data from db
Finally
da.Dispose() 'in case something goes wrong
End Try
Dim startVal = 0 'first record
Dim endVal = ds.Tables(0).Rows.Count 'total number records
For var = startVal To endVal - 1 'display records
Console.WriteLine(ds.Tables(0).Rows(var).Item(0).ToString() + " " + ds.Tables(0).Rows(var).Item(1).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString()) 'code for display id and name
Next
Return ds
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Module
I would like to know what is the cause of the error so that I can proceed to my program.. Thank you so much for the feedback..
You seem to be missing a delimiter after your password attribute.
I think you also need to use Jet OLEDB:Database Password=... instead (if indeed you have an access database protected with a password):
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb;" _
& "Jet OLEDB:Database Password=oNer00FooR3n0;"
Missing ; delimiter here:
...Password=oNer00FooR3n0 " & "Data Sourc...
Needs to be
...Password=oNer00FooR3n0 " & ";Data Sourc...
Also just Password instead of Database Password.
Initially, i too got this sort of error, but when i wrote the connection string in a single line (i mean without using [& _] or breaking in 2 lines, then this worked properly.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\USER1\Desktop\MSaccessDB\MSaccessDB\my_database_file.mdb;Database Password=MyPassword"
Hope this helps.
Mukesh L.