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)
Related
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
I have created a function in a module to connect to database for a windows application
Imports System.Data.SqlClient
Module mod_main
Public Function connectDB() As SqlConnection
Dim Connection As New SqlConnection
Try
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
If IntegratedSecurity Then
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;Integrated Security=True"
Else
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;User ID='" & usr & "';Password='" & pwd & "'"
End If
Connection.Open()
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Module
I have so many functions and classes that uses plethora of db activities for that I use aforementioned connection function.For exmample:
Public Sub FillComboBox(ByVal ComboBox As C1.Win.C1List.C1Combo, ByVal Query As String, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim SourceDataSet As New DataSet
Dim adapter As New SqlDataAdapter(Query, connectDB) /*Assigning connection here */
adapter.Fill(SourceDataSet)
ComboBox.DataSource = SourceDataSet.Tables(0)
ComboBox.ColumnHeaders = False
ComboBox.ColumnWidth = 0
ComboBox.ExtendRightColumn = True
ComboBox.DisplayMember = DisplayMember
ComboBox.ValueMember = ValueMember
End Sub
Since I'm a beginner in programming my question is , Is this a correct way of handling db connection?
I suggest you to make following changes:
make Connection as public for global accessibility
save connection string in config file and access it from there
need not to close and re open connection open connection only when there is no available connection
In your case all time it creates a new connection when the function is
invoked since you are declaring and initializing connection inside the
function. so checking connection state is meaning less:
so your function looks like following:
public Connection As New SqlConnection
Public Function connectDB() As SqlConnection
Try
Dim Constr As String =""
If IntegratedSecurity Then
Constr = ConfigurationManager.AppSetting("IconnectionString")
Else
Constr = ConfigurationManager.AppSetting("connectionString")
End If
If Connection Is Nothing Then
Connection = New SqlConnection(Constr)
End If
If Connection.State <> ConnectionState.Open Then
Connection.Open()
End If
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
Below is the code for fetching the data into textbox but its not working it shows error no data exits row/column whereas data and datafield are perfectly alright.
Please help.
Dim Connection As OleDbConnection
Connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/db/QardanHasana.mdb"))
Connection.Open()
Dim ejamaatregcmd As OleDbCommand
Dim ejamaatregdtrdr As OleDbDataReader
ejamaatregcmd = New OleDbCommand("SELECT ITSData.[EJamaatID], ITSData.[ITSFirstName] FROM ITSData WHERE EjamaatID= #EjamaatID", Connection)
ejamaatregcmd.Parameters.Add(New OleDbParameter("#EjamaatID", txtEjamaatID.Text))
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.HasRows Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
end if
A DataReader needs a call to Read to position itself on the first record retrieved
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.HasRows Then
ejamaatregdtrdr.Read()
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
By the way, Read returns false if there are no rows to read, so you could remove the test for HasRows and write simply
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
Another suggestion to improve your code is to start using the Using Statement
Using Connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;....")
Using ejamaatregcmd = new OleDbCommand("SELECT ITSData.[EJamaatID], ITSData.[ITSFirstName] FROM ITSData WHERE EjamaatID= #EjamaatID", Connection)
Connection.Open()
ejamaatregcmd.Parameters.Add(New OleDbParameter("#EjamaatID", txtEjamaatID.Text))
Using ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
End Using
End Using
End Using
The using statement is invaluable to help you to close and dispose the disposable objects like the connection, the command and the reader. Lacking a proper dispose your code uses more memory and locks resources resulting in a more unstable application.
Before reading data from a DataReader, you need to move the row to the first row by calling the Read method. It returns true if data exist, so you don't need to check the HasRows property:
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.Item("ITSFirstName").ToString()
End if
I'll generally do something like the following
Function GetResult(ID As string) As String
GetResult = "No Data" 'Default Result
Dim conn As System.Data.OleDb.OleDbConnection = *NewConnectionObject*
Dim comm As System.Data.OleDb.OleDbCommand = *NewCommmandObject*
comm.Parameter.AddWithValue("#Parametername",ID)
Using reader As System.Data.OleDb.OleDbDataReader = comm.ExecuteReader()
If reader.HasRows Then
'Reader has data, so iterate through it
GetResult = ""
while reader.read
GetResult += reader("FirstName")
End While
Else
'Either Do Nothing - Default Result will show
'Throw New System.Exception("Empty Data") 'Try Catch Statement have overhead.. so it's not a popular methodology
'Or Log Something..
End If
End Using
If conn.state = connection.open Then
conn.close
End
End Function
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.