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.
Related
I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)
I have, for over a month, tried in vain to resolve this. I am using SQLite and trying to write a simple check to see if i can connect to the database. I found some code here that was supposed to do just that.
Public Function ConnExist(strDB) As Boolean
Dim SQLconnect As New SQLite.SQLiteConnection()
Try
Using Query As New SQLiteCommand()
SQLconnect.ConnectionString = "DataSource=" & strDB & ";Version=3;New=False;Compress=True;"
SQLconnect.Open()
With Query
.Connection = SQLconnect
.CommandText = "SELECT * FROM tbltest"
End With
Query.ExecuteNonQuery()
SQLconnect.Close()
End Using
'SQLconnect.ConnectionString = "Data Source=" & strDB & ";Version=3;New=False"
'SQLconnect.Open()
'SQLconnect.Close()
Catch ex As Exception
MsgBox(ex.Message)
'Return False
End Try
Return True
End Function
I know the database is at the location specified. On the SQLconnect.Open() part it errors out and tells me datasource cannot be empty. I opened the database using DB Browser and it is not corrupt. What am I doing wrong?
This is how I build my connection string for SQLite.
Dim constr As String = "Data Source=""" & FullFilePath & """;Pooling=true;FailIfMissing=false"
Think you are just missing the Double Quotes around the path.
Public Function ConnExist(strDB) As Boolean
Dim cs As String
Dim cnn As New SQLiteConnection
Dim cmd As New SQLiteCommand
cs = "Data Source=" & strDB & ";Version=3;New=False;"
If (IO.File.Exists(strDB)) Then
cnn = New SQLiteConnection(cs)
Try
cnn.Open()
cmd = cnn.CreateCommand()
cmd.CommandText = "SELECT * FROM tblSettings"
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
cnn.Dispose()
Catch ex As Exception
Return False
Exit Function
End Try
Else
Return False
Exit Function
End If
Return True
End Function
This is my code, I m getting error "There is no row at position 0."
Sub loadservicetype()
Dim str As String = "SELECT servicename FROM tbl_activity WHERE activity= '" & CmbActivity.Text & "' "
Dim dt As New DataTable
Dim sdr As New SqlDataAdapter(str, connection)
sdr.Fill(dt)
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End Sub
First thing is Always Use SQL Parameter to AVOID SQL injection
Like this
Dim commandText As String = "SELECT servicename FROM tbl_activity WHERE activity=#ID"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
command.Parameters.Add("#ID", SqlDbType.Int).Value = ID
Try
connection.Open()
Dim rowsAffected As String = command.ExecuteNonQuery()
Catch ex As Exception
throw
End Try
End Using
MSDN SOURCE
Your DataTable is Doesn't Return any rows which You Are Trying to Access
If dt IsNot Nothing Then
If dt.Row.Count>0 Then
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End If
End If
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.SelectCommand = dbcommand 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