Windows Forms application using VB.Net and VS2012. Connecting to an Access database using Access Runtime 2013. The app is compiled to target x86. The problem is intermittent and occurs on multiple different PC's randomly, and accessing a database on a local hard drive.
Using cn As New OleDbConnection
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
If Not OpenDBConnection(cn) Then
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
MsgBox("Unable to make database connection to update screen status.", MsgBoxStyle.OkOnly, "Database Connection Error (MMUN1)")
Exit Sub
End If
'continue processing....
end using
Public Function OpenAccessConnection(ByRef conn As OleDb.OleDbConnection) As Boolean
Dim builder As New OleDbConnectionStringBuilder()
'conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Try
builder.ConnectionString = "Data Source=" & DPATH & DBNAME
builder.Add("Provider", "Microsoft.ACE.OLEDB." & ACCESSVER & ".0") 'ACCESSVER is '12'
conn.ConnectionString = builder.ConnectionString
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
conn.Open()
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
Return True
Catch ex As Exception
MsgBox("Unable to make Access connection. Error# " & Err.Number & " " & ErrorToString() & " " & ex.ToString, MsgBoxStyle.OkOnly, "Database Connection Error (OLEOPN1)")
Return False
Finally
builder.Clear()
builder = Nothing
End Try
End Function
Public Function OpenDBConnection(ByRef conn As OleDbConnection) As Boolean
'I know this is an extraneous function call but it is in transition from multiple prior uses and I thought I had better not exclude it from this post in case it mattered for some reason
OpenDBConnection = OpenAccessConnection(conn)
End Function
Error being returned intermittently:
I have read many of the posts on this topic and have not found a solution, and frankly am not sure where to look. Could this be coming from an earlier application error? Thread/STA issue? If so, what do I do about it? On the development machine, I will on occasion see a DisconnectedContext error, but have not seen the External component error which appears on PC's running the released version. Are these related? Also, there are some ADO (ADODB) connections being made to the database (still trying to replace/upgrade), but these are not open at the time this new connection is being made. But could it be a connection pooling issue? Thanks in advance for any help out there.
Related
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
I retrieve it in my mainform:
Try
rs.Connection = con
cmd = "select * from cdcol.currency_rate"
rs.CommandText = cmd
res = rs.ExecuteReader
While res.Read
Dim currency = res.GetString("currency")
ComboBox2.Items.Add(currency)
End While
res.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
and this in my tabcontrol
Try
rs.Connection = con
cmd = "select * from cdcol.currency_rate where currency='" & ComboBox2.Text & "'"
rs.CommandText = cmd
res = rs.ExecuteReader
While res.Read
If sell.Checked = True Then
buy.Text = res.GetDouble("buy_rate")
coderate.Text = res.GetString("code")
End If
If buy.Checked = True Then
sell.Text = res.GetDouble("sell_rate")
coderate.Text = ("PHP")
End If
End While
res.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
when i log in there was an error,
what's wrong with my codes ?
please help me ..
A few things could be going on, hard to tell without all the code but I'll give you some ideas. I'm assuming this is a WinForms app (also assuming this is SQL Server)?
If you've verified that all your DataReader's are being closed properly then it is possible that you have two DataReaders actually trying to read at the same time if they're using a shared connection in your program (you say you're using a tab control and executing a query, if you have one reader running somewhere and then you click on a tab you could run into that scenario). If that is your desired behavior you can allow multiple recordsets by adding the multiple active result sets flag to your connection string:
https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx
Something like this:
Dim connectionString As String = "Data Source=MSSQL1;" & _
"Initial Catalog=AdventureWorks;Integrated Security=SSPI;" & _
"MultipleActiveResultSets=True"
The MSDN article gives you much more info about it. In your scenario this will probably work. MSDN offers this though (which is your other option, use a connection per method you need it and dispose of it when you're done):
"MARS is not designed to remove all requirements for multiple
connections in an application. If an application needs true parallel
execution of commands against a server, multiple connections should be
used."
I opened the older app in VS 2010 and made changes based on the recommendations in the error statements that popped up. However one part that is still not working is shown below.
The error that comes back is
"file is already opened exclusively by another user or you need permission to view it"
I am opening up an access database and " select" and put it in an excel worksheet. The name of the worksheet changes every time the app is used.
This worked in 2003 but not in 2010. I have goggled this and none of the answers have worked.
Dim AccessConn8 As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=c:\UpdateExportFile\ExportFile.mdb")
AccessConn8.Open()
Dim AccessCommand8 As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Excel " & _
"5.0;DATABASE=c:\" & strfilename & ".xls;HDR=YES;].[sheet1] from ExcelExport", AccessConn8) '
Try
AccessCommand8.ExecuteNonQuery()
Catch exe As DataException
Catch exc As System.Exception
MsgBox("EXCEL not updated. Contact your System Administrator. " & strfilename)
MsgBox(" ----> " & exc.Message)
AccessConn8.Close() ' added sat 2/23/15
Exit Sub
End Try
AccessConn8.Close()
Dim obook As Microsoft.Office.Interop.Excel.Workbook
Dim oexcel As Microsoft.Office.Interop.Excel.Application
oexcel = CType(CreateObject("Microsoft.Office.Interop.Excel.Application"), Microsoft.Office.Interop.Excel.Application)
obook = oexcel.Workbooks.Open("c:\" & strFileName & ".xls")
Try
With oexcel
.Visible = False
.Range("C1").Value = "'Store #"
.Range("D1").Value = "'Vendor #"
End With
Catch ex As Exception
MsgBox("error:" & ex.ToString, MsgBoxStyle.Critical, "ERROR")
End Try
' added
Dim myrange As Excel.Range
myrange = oexcel.Range("a1:l90")
myrange.Sort(Key1:=myrange.Range("c1"), Order1:=Excel.XlSortOrder.xlAscending, Header:=Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes, Orientation:=Excel.XlSortOrientation.xlSortColumns)
obook.Save()
obook.Close()
oexcel.Quit()
Can you help me downed the right path to an answer?
I cannot be sure but I suspect that this behavior is caused by connection pooling that keeps the connection (and perhaps the file) open also after you have tried to close it.
I suggest two changes to your code above, all around the connectionstring and the way in which you open close the connection
Using AccessConn8 As New OleDbConnection("...;OLE DB Services = -2;")
AccessConn8.Open
......
' Code as above....
......
End Using
The OLE DB Services = -2 disables the automatic use of Connection Pooling for this connection, while the Using Statement ensures that the connection is closed and DISPOSED after you have finished to use it
When I am trying to compact my Access 2010 database (no password), I am getting the error message Class Not Registered I am using Visual Studio 2010, and I have not idea what this problem is. Here Is the code i'm using:
Private Sub Compactdb()
Dim JRO As JRO.JetEngine
JRO = New JRO.JetEngine
'The first source is the original, the second is the compacted database under an other name.
JRO.CompactDatabase("Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Ex.mdb; Jet OLEDB:Engine Type=5", "Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Temp.mdb; JetOLEDB:Engine Type=5")
'Original (not compacted database is deleted)
System.IO.File.Delete("C:\Forte\Ex.mdb")
'Compacted database is renamed to the original databas's neme.
Rename("C:\Forte\Temp.mdb", "C:\Forte\Ex.mdb")
'User notification
MsgBox("The database was compacted successfully")
End Sub
If I change the Jet.OLEDB.5.0 to 4.0 I get a different error message of Unrecognized databse format
Try
Dim ParentCNN As String
Dim CloneCNN As String
Dim JrO As New JRO.JetEngine
ParentCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Fortedb.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;"
CloneCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Temp.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;Jet OLEDB:Engine Type=5"
'If cnnMDE.State = ConnectionState.Open Then
' cnnMDE.Close()
'End If
JrO.CompactDatabase(ParentCNN, CloneCNN)
If System.IO.File.Exists("C:\Forte\Temp.accdb") Then
System.IO.File.Delete("C:\Forte\Fortedb.accdb")
Rename("C:\Forte\Temp.accdb", "C:\Forte\Fortedb.accdb")
End If
Catch ex As Exception
MainTextBox.AppendText(Environment.NewLine & "Database Compression Failure :" & vbCr & ex.Message)
End Try
Tried seemingly everything here to get this to work but I keep getting "Keyword not supported" errors for just about every iteration of dsn-less connection strings I can find out there in internet land, two are shown below.
Public cnSystem As New SqlClient.SqlConnection
Public Sub ConnectToSQL()
Dim sConnectionString As String
Dim sServer As String
Try
'Always connect to production server to get startup environment variables
If gbIsProduction Then
If gsProductionServer = "" Then
sServer = "xxxxx-SQL"
Else : sServer = gsProductionServer
End If
Else : sServer = gsDevelopmentServer
End If
//Doesn't work
sConnectionString = "Network Library=DBMSSOCN;Data Source=xxxxx-SQL,1433;Inital Catalog=xxxxx;User ID=sa;Password=xxxxx;"
//Doesn't work
sConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;UserId=sa;Initial Catalog=xxxxx;Data Source=xxxxx-SQL;Password=xxxxx;"
cnSystem.ConnectionString = sConnectionString
cnSystem.Open()
cmdSystem.Connection = cnSystem
Catch ex As Exception
RaiseError("", "modGeneral." & System.Reflection.MethodBase.GetCurrentMethod().Name, Err.Number, Err.Description)
End Try
End Sub
Any ideas on what is the proper connection string for a DSN-less connection to a SQL server using the data objects I am using?
Thanks!
While not the exact answer, this website helps me all the time:
http://www.connectionstrings.com/
Also, when using System.Data.SQLClient you do not have to specify the provider and I believe you will get the error you are receiving. Remove that part.
try creating a udl file to create your connection string. then you can test it to ensure it is working - http://www.codeasp.net/blogs/hajan/microsoft-net/857/working-with-udl-universal-data-link-files