How to close database connection? - vb.net

I'm having a problem in project of mine in VB.NET. The problem is whenever I want to save, delete or update data with an Access database I get an error with a message saying that "not allowed to change the connection string property. connection's current state is open".
I have used If con.State = ConnectionState.Open Then con.Close() End If
command using finally in every section where I have called the database.
But still I'm having the same problem. What am I doing wrong?

Use the "USING"-Keyword. Exiting a using block calls .Dispose() on the object which for a SqlConnection will close the connection and any open resources.
Using connection As New SqlConnection(connection)
Dim command As New SqlCommand("Select * From dbo.table1",connection)
command.ExecuteNonQuery()
End Using
EDIT:
Module Module1
Public Sub DbConnection()
Dim connectionString as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourServerAddress;Initial Catalog=university.mdb;
Integrated Security=SSPI;"
Using connection as New Sqlconnection(connectionstring)
Dim command As New SqlCommand("Select * From dbo.table1",connection)
command.ExecuteNonQuery()
End Using
End Sub
End Module

Related

"No value given for one or more required parameters" error using OleDbCommand

I am trying to update a record in MS Access using VB.net. This code will be under the "Delivered" button. When I try to run it, it shows the "No value given for one or more required parameters" error. Here is my code:
Private Const strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Traicy\Downloads\MWL(11-30-2021)\MadeWithLove\MadeWithLove\MadeWithLove.mdb;"
ReadOnly conn As OleDbConnection = New OleDbConnection(strConn)
Dim cmd As OleDbCommand
Public Sub DeliveredUpdate()
Const SQL As String = "UPDATE DELIVERY SET delivery_status = #status"
cmd = New OleDbCommand(SQL, conn)
' Update parameter
cmd.Parameters.AddWithValue("#status", "Delivered")
' Open connection, update, then close connection
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
conn.Close()
End Try
End Sub
Do not declare connections or commands outside of the method where they are used. These database objects use unmanaged resources. They release these resources in their Dispose methods. The language provides Using blocks to handle this.
As mentioned in comments by Andrew Morton, you should have a Where clause to tell the database which record to update. This would contain the primary key of the record. I guessed at a name for the field, OrderID. Check your database for the real field name.
Access does not use named parameters but you can use names for readability. Access will be able to recognize the parameters as long as they are added to the Parameters collection in the same order that they appear in the sql string. In some databases the Add method is superior to AddWithValue because it doesn't leave the datatype to chance.
It is a good idea to separate your database code from your user interface code. If you want to show a message box in your Catch put the Try blocks in the UI code. This way your function can be used in a web app or mobile app without rewriting.
Public Function DeliveredUpdate(ID As Integer) As Integer
Dim recordsUpdated As Integer
Dim SQL As String = "UPDATE DELIVERY SET delivery_status = #status Where OrderID = #Id;"
Using conn As New OleDbConnection(strConn),
cmd As New OleDbCommand(SQL, conn)
cmd.Parameters.Add("#status", OleDbType.VarChar).Value = "Delivered"
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = ID
conn.Open()
recordsUpdated = cmd.ExecuteNonQuery
End Using 'closes and disposes the command and connection
Return recordsUpdated
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim retVal As Integer
Dim id As Integer = 1 'not sure where you are getting this value from
Try
retVal = DeliveredUpdate(id)
Catch ex As Exception
MsgBox(ex.Message)
End Try
If retVal > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
End Sub

In vb.net project, how to check if SQL connection is still available and end all processing?

I have a problem in a vb.net Windows Form project. My company is having network issues and is losing connection between the Windows Form application and the SQL server. When this happens, the application locks up and closes. Before any SQL commands are executed, is there a way to check if the SQL connection is even available?
I've tried using this:
If (cmd.Connection.State <> ConnectionState.Closed)
after the cmd is setup like this:
Dim cmd As SqlCommand
cmd = MSSQL_CONN.CreateCommand
but the state is often Open because the network connection fails after the SQL command was initialized.
I've tried to catch the error like this:
Private m_conn As SqlConnection
Try
m_conn = New SqlConnection(cn_str)
Call m_conn.Open()
Catch e As Exception
MessageBox.Show("Error")
If MSSQL_CONN.TransactionStarted Then
MSSQL_CONN.RollbackTransaction()
End If
End Try
but this has problems because it's trying to do a rollback for any other errors and the rollback throws an error because of the loss of connection state. This also starts a cascade into other timers and background processes that continue to run and try to connect to the SQL server.
I'm hoping there something like
If *SQL connection is even still available* Then
Call m_conn.Open()
Else
*Don't execute any other SQL on this form or any other background forms*
End If
Normally it's best to use a using statement for a connection where the connection is scoped to the method you are working with the database. Otherwise you could create the connection as needed e.g. check the connection state as on error.
Public Class DataOperations
Public Shared Async Function Connection() As Task(Of SqlConnection)
Dim cn As New SqlConnection With {.ConnectionString = "TODO"}
Try
Await cn.OpenAsync()
Return cn
Catch ex As Exception
Return New SqlConnection
End Try
End Function
End Class
Then there is locally scoped where the choice is OpenAsync or Open.
Public Shared Function GetCatagories() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection With {.ConnectionString = "TODO"}
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = "TODO"
Try
cn.Open()
dt.Load(cmd.ExecuteReader())
Catch ex As Exception
' decide on how to handle
End Try
End Using
End Using
Return dt
End Function
EDIT:
Public Shared Async Function IsServerConnected() As Task(Of Boolean)
Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
Try
Await cn.OpenAsync()
Return True
Catch ex As Exception
Return False
End Try
End Using
End Function

How do I deal with "An attempt has been made to free an RCW that is in use. " Error

I know this question might be duplicate questions but I have a problem and need a solution to overcome it.
I've made a project and used functions and Sub everywhere.
One of the function/Sub is like,
Public Sub ExecuteQuery(Xcn As OleDbConnection)
Try
If Xcn.State = ConnectionState.Open Then Xcn.Close()
Xcn.Open()
cmd.Connection = Xcn
cmd.ExecuteNonQuery()
Xcn.Close()
Catch e As Exception
Throw e
End Try
End Sub
I just use executequery(con) instead of writing whole sentence everytime.
Now the question is that I created a bw_worker and running a sub that includes small subs like I showed above asynchronously.
For example, A sub is that I run async like,
Private Sub RunCode()
dim cmd as new oledbcommand("Select * from table",con)
if con.state = ConnectionState.closed then con.open()
execute reader stuff here
if con.state = ConnectionState.Open then con.close()
ExecuteQuery(con)
cmd = new Oledbcommand("Select * from Table2",con)
ExecuteQuery(con)
End Sub
I don't know if its good practice or not but now problem arises.
I am trying to create a loading screen for some time taking functions and subs so I referred this Link and faced the error.
NOTE: I understood the error it gives but I want to know a workaround if possible. Like something possible without changing a lot of code.
If you keep your database objects local they won't be open on another thread. Commands too. This code will demonstrate how to use Using blocks which will close and dispose of your database objects even if there is an error. Please no .AddWithValue. The .Add method forces you to name a datatype which will help with visually providing a clue that the datatype passed in matches. There are also several database reasons to use .Add. See https://www.dbdelta.com/addwithvalue-is-evil/ and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
It is okay to have a class level variable for the connection string so you don't have to type it all the time.
Private ConnString As String = "Your connection string"
Private Sub RunCode()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand("Select * from table", con)
con.Open()
Using reader = cmd.ExecuteReader
'reader stuff here
End Using
End Using
End Using
End Sub

Why do I got error when I create 2 commands on SQL in vb.net

Should I use using?
Private Sub btntest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btntest.Click
If sqlConnection.State = ConnectionState.Closed Then
sqlConnection.Open()
End If
Dim query = "Select * from tablebusiness"
Dim cmd = New MySqlCommand(query, sqlConnection)
Dim data = cmd.ExecuteReader()
Do While data.Read
Loop
Dim cmd1 = New MySqlCommand(query, sqlConnection)
Dim data1 = cmd1.ExecuteReader //Error. Already have data reader
//Error There is already an open DataReader associated with this Connection which must be closed first.
Dim check = 1
'sqlConnection.Close()
End Sub
Although you have not let us know what the error is (which makes solving any problem much harder), I expect the issue is arising because you are trying to re-use the SqlConnection object for 2 different commands. Especially since you are not disposing your first command before initialising the second.
Firstly, use 2 different SqlConnection objects to manage the connection to the database. You are not putting any more overhead on the database or the code if you do this. Let the .NET framework connection pooling do its job - don't try to do it yourself. You don't need to do anything specific to enable connection pooling (although you can disable it by setting Pooling=false in your connection string).
Secondly use the using statement to correctly dispose your SqlConnection, SqlCommand, and SqlDataReader objects. e.g.
Using connection As New SqlConnection(connectionString)
connection.Open()
Using Command As New SqlCommand(query, connection)
Using reader As SqlDataReader = Command.ExecuteReader()
While reader.Read()
'Do Stuff'
End While
End Using
End Using
connection.Close()
End Using
You have missed the parenthesis after cmd1.ExecuteReader. It should be cmd1.ExecuteReader().
You Need another Conncetion if you want both the datareaders to work simultaneously, else close/ dispose the previous command before using cmd1.ExecuteReader()

vb.net - sharing mdb access connection among multiple forms

I'm starting to put in a database into my application, however I'm drawing a blank on how to share a database connection among the dozen or so different forms in my MDI application. I'm assuming this has to do with interfaces or something but I can't find any relevant examples anywhere. Can someone help me out? Ideally what I'd like is when the app is loaded up there is a call to a function in the forms loading area which establishes a single connection to the mdb, that I can then call via any form so I don't always have to open/close connections everytime I need to update the db (assuming what I'm suggesting is better for overhead), unless that is a better option?
Here's a basic example of the mdb database access code I've got working:
Dim dt As DataTable = New DataTable()
Dim OleDbTran As OleDbTransaction = Nothing
Using connJET As OleDbConnection = New OleDbConnection("connection string here...")
Try
connJET.Open()
Dim sqlCount As OleDbCommand = New OleDbCommand("select * from mytable", connJET)
Using aReader As OleDbDataReader = sqlCount.ExecuteReader()
dt.Load(aReader)
End Using
If (dt.Rows.Count > 0) Then
MsgBox(dt.Rows.Count)
End If
OleDbTran = connJET.BeginTransaction()
Dim aCommand As OleDbCommand = connJET.CreateCommand()
aCommand.CommandText = "INSERT INTO Programs (title) VALUES (#title)"
aCommand.Transaction = OleDbTran
aCommand.Parameters.Add("#title", OleDbType.VarChar)
aCommand.Parameters("#title").Value = "Test"
aCommand.ExecuteNonQuery()
OleDbTran.Commit()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
Assuming that you create the connection in your startup form, then you could just add constructors to the other forms that accept a SqlConnection and send that in whenever you create an instance of that form.
Or if you prefer, you create something like this:
Public Class Connection
Private Shared connection As OleDb.OleDbConnection
Public Shared ReadOnly Property Instance As OleDb.OleDbConnection
Get
If connection Is Nothing Then
connection = New OleDb.OleDbConnection("connstring")
End If
Return connection
End Get
End Property
End Class
And then you could access it by just calling Connection.Instance whenever you need it.