could not update currently locked vb.net error - vb.net

I want to Insert 2 different data in 2 different table of ms-access.
And it shows this error.
I have a code like this:
try
dim sql1,sql2 as string
sql1 = "INSERT INTO table1(something)VALUES(something)"
cmd = new oledbcommand(sql1, connection)
cmd.executenoquery()
sql2 = "INSERT INTO table2(something)VALUES(something)"
cmd2 = new oledbcommand(sql2, connection)
cmd2.executenoquery()
catch ex as exception
msgbox(ex.tostring())
(where these cmd1,cmd2 are defined in controlModule.)
so,what should I do ?
Any help is appreciated. Thank You

I think closing the connection fixes the issue, best by using the Using-statement:
try
Using con As OleDbConnection = GetConnection() ' or New OlebConnection(...)
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table1(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using con As OleDbConnection = GetConnection()
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table2(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
msgbox(ex.tostring())
End Try

This is a concurrency issue. Because some other part of your code or MS Access itself accesses the database at the same time.
The fact is that you're not closing the connection after it's use. So the 2nd call should fail with that exception. Instead, you should wrap your disposables - e.g. the OleDbConnection, commands, etc. - in a using statement. That way, the connection will be closed, even if an exception occur:
Using con As New OleDbConnection, cmd1 As OleDbCommand = con.CreateCommand, cmd2 As OleDbCommand = con.CreateCommand()
cmd1.CommandText = "INSERT INTO table1(something)VALUES(something)"
cmd1.ExecuteNonQuery()
cmd2.CommandText = "INSERT INTO table2(something)VALUES(something)"
cmd2.ExecuteNonQuery()
End Using

Related

How to fix the connectionstring property has not been initialized

I am trying to create a user and insert the data into a MS Access database, but I get an error:
The connectionString property has not been initialized
whenever I click on the button.
I have tried all possible codes on Connection string but the challenge still persist.
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
sqlquery.Connection = sqlconn
con = New OleDbConnection(conString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sql, con)
sqlquery.CommandText = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
sqlquery.Parameters.AddWithValue("New ID", txtNewID.ToString)
sqlquery.Parameters.AddWithValue("Name", txtName.ToString)
sqlquery.Parameters.AddWithValue("Gender", txtGender.ToString)
sqlquery.Parameters.AddWithValue("Address", txtAddress.ToString)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataTable
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "con")
Return
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
That code really is a mess. It should be reduced to this and that will fix your issue:
Try
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"),
command As New OleDbCommand("INSERT INTO member (mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#mmbr_id, #name, #gender, #address, #phone, #join_date, #acc_no)", connection)
With command.Parameters
.AddWithValue("#mmbr_id", txtNewID.Text)
.AddWithValue("#name", txtName.Text)
.AddWithValue("#gender", txtGender.Text)
.AddWithValue("#address", txtAddress.Text)
'Set other parameters here.
End With
connection.Open()
command.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Ideally, you would be using Add rather than AddWithValue too, but that's another conversation.
Here is simple code for what you mostly asked for, in addition to the whole open source on this link:
enter link description here
Here is the tested code:
Private Sub BtnAddNewRec_Click(sender As Object, e As EventArgs) Handles BtnAddNewRec.Click
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\db1.mdb"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Tbl1 (mmbr_id, name, gender, address) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress)"
cmd.Parameters.AddWithValue("#txtNewID", txtNewID.Text)
cmd.Parameters.AddWithValue("#txtName", txtName.Text)
cmd.Parameters.AddWithValue("#txtGender", txtGender.Text)
cmd.Parameters.AddWithValue("#txtAddress", txtAddress.Text)
cmd.ExecuteNonQuery()
MsgBox("Record Added Successfully!")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
I hope this helps:
The trouble here is that you have 2 commands in your code, namely cmd and sqlquery. You define sqlquery at the beginning of the code, then initialize cmd with the connection and a SQL variable that I cannot determine the source of.
What you need to do is redo this part and get remove the extra references that seem to be the source of the problem. Consider the following...
Try
Dim conString As String
Dim text = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
Using sqlCon = New OleDbConnection(conString), sqlCmd = New OleDbCommand(text, sqlCon)
With sqlCmd.Parameters
.AddWithValue("New ID", 234234)
.AddWithValue("Name", "Fabulous")
.AddWithValue("Gender", "Male")
.AddWithValue("Address", "127.0.0.1")
End With
sqlCon.Open()
sqlCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
I couldn't tell whether txtNewID and the other similarly named variables are text boxes or not. If they are text boxes, you need the .Text property which gets the content in a string. You'll need to replace the literals I used in my test environment to get to it.
Ensure everything, including your connection string and query are correct for this to run smoothly. In your current case, you are getting the connection string related error because you are attempting to execute the query on a connection you didn't associate with the connection.

Automatically closed db connection within using statement

I wrote this code to write my data into a database
Public Class SQL_Client
Sub AddData(ByRef myGDI As GeneralInfo)
Dim conStr As String = "Server=NB01009;Database=DEV_DW;Trusted_Connection=true"
Dim query As String = String.Empty
query = "INSERT INTO GeneralInfo(id, name, data) VALUES (#id, #name, #data)"
Using con As SqlConnection = New SqlConnection(conStr)
Using comm As New SqlCommand
With comm
.Connection = con
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#id", myGDI.id)
.Parameters.AddWithValue("#name", myGDI.name)
.Parameters.AddWithValue("#data", "Hallo Data")
End With
Try
con.Open()
comm.ExecuteNonQuery()
Catch ex As SqlException
Console.WriteLine(ex.Message.ToString(), "Error Message")
End Try
End Using
Dim subquery As String = String.Empty
query = "INSERT INTO FullData(GeneralInfoID, userRunID VALUES(#GeneralInfoID, #userRunID)"
For Each myData As FullData In myGDI.data
Using command As New SqlCommand
With command
.Connection = con
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#GeneralInfoID", myGDI.id)
.Parameters.AddWithValue("#userRunID", myData.userRunID)
End With
Try
con.Open()
command.ExecuteNonQuery()
Catch ex As SqlException
Console.WriteLine(ex.Message.ToString(), "Error Message")
End Try
End Using
Next
End Using
End Sub
End Class
Since I have a nested object I want to write into the database (see here) I use a loop and a seconed Using Statement. At the second command.ExecuteNonQuery() it get the undhandled Exception:
System.INvalidOperationException: 'The connection was not closed. The connection's current state is open.'
I actually thought that after leaving the Using statement the connection would be closed automatically. But it looks like this assumption was wrong. Could anyone tell me how to handle this correctly?
You're opening the connection twice before the connection is closed.
It will automatically be closed after the last End Using.
Remove the second con.Open() and it should be fine.

How to refresh GridView's data after update or delete operation in case of , GridControl.datasource = Datatable in Devexpress

I have a devexpress gridview that is related to a table in a sql server database. I am trying to refresh the gridview right after performing a delete but nothing I've tried so far has worked. (I've verified that the delete operation has worked in the table). I've tried 3 ways of updating the gridview but nothing has worked:
GridControl1.Refresh()
GridView1.RefreshData()
GridControl1.RefreshDataSource()
GridView1.RefreshEditor(True)
Here is the complete code of the whole operation:
Using cnn As New SqlConnection(FrmGeneralConfig.GetInstance.getConnection())
Try
cnn.Open()
Dim daDelete As New SqlDataAdapter
Dim command As SqlCommand = New SqlCommand("DELETE FROM Client_Excepte_Charge_Min WHERE ClientNo = #ClientNo", cnn)
command.Parameters.AddWithValue("#ClientNo", clientNo)
daDelete.DeleteCommand = command
daDelete.DeleteCommand.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
MessageBox.Show("Erreur: " & ex.Message)
Finally
GridControl1.Refresh()
GridView1.RefreshData()
GridView1.RefreshEditor(True)
End Try
End Using
You need to update your DataTable after deleting the rows in server.
Here is example:
Using cnn As New SqlConnection(FrmGeneralConfig.GetInstance.getConnection())
Try
cnn.Open()
Dim command As SqlCommand = New SqlCommand("DELETE FROM Client_Excepte_Charge_Min WHERE ClientNo = #ClientNo", cnn)
command.Parameters.AddWithValue("#ClientNo", clientNo)
command.ExecuteNonQuery()
dtExceptions.Clear()
Using adapter As New SqlDataAdapter()
Dim selectCommand = New SqlCommand("SELECT * FROM Client_Excepte_Charge_Min", cnn)
adapter.SelectCommand = selectCommand
adapter.Fill(dtExceptions)
End Using
cnn.Close()
Catch ex As Exception
MessageBox.Show("Erreur: " & ex.Message)
End Try
End Using

Update MS Access via vb.net

the below code runs without error, but the MS Access table isn't updating. What am I missing?
Try
cnn = New OleDbConnection(ConfigurationManager.ConnectionStrings("accConnectionString").ToString())
cnn.Open()
Catch ex As Exception
Debug.Print("Oops - no connection to database")
Exit Sub
End Try
Dim sql As String
sql = "SELECT * FROM tblSend WHERE UploadedSuccessfullyOn is null ORDER BY QueuedOn;"
Dim da As New OleDbDataAdapter(sql, cnn)
Dim ds As New DataSet
da.Fill(ds, "dsQueuedToSend")
For Each dr As DataRow In ds.Tables("dsQueuedToSend").Rows
' Perform other unrelated tasks in this space, removed for brevity
' If those other tasks were successful, update Access.
If success = True Then
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #uploadedOn WHERE (([UploadID]) = #uploadId);"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.Parameters.Add("#uploadedOn", OleDbType.Date).Value = Now
cmd.Parameters.Add("#uploadedId", OleDbType.Integer).Value = dr("UploadID")
cmd.ExecuteNonQuery()
cmd.Dispose()
Console.WriteLine("Success: updated.")
Else
Console.WriteLine("Failed: Not updated.")
End If
Next
da.Dispose()
cnn.Close()
I've also tried with:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = ? WHERE (([UploadID]) = ?);"
Or simply add the values in the not-preferred/non-parameter approach:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #" & Now & "# WHERE (([UploadID]) = " & dr("UploadID") & ");"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
None of these approaches updates the MS Access table. Ideas? Thanks!
One thing I have been caught by before with Visual Studio is that when embedding an Access database in a WinForms project, when you run the project, the Access database is copied over from the original to the runtime directory, overwriting any changes you've made.
This can create the illusion that an update is not taking place, when in fact if you check at the right moment, it is.

SQL Update with where clause with variables from VS2010 Winforms

I am trying to do an update query from a winform with two variables without using a dataset.
I assign both of my variable and then run the query but it keeps giving the error that zcomp is not a valid column name. Which of course is true but I tell it which column before I say = zcomp. Below is my code that is running the query.
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - zamnt WHERE [ComponentID] = zcomp"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
I have tried it several different ways. It works just fine if I take out the zamnt and zcomp and put the actual number values that are in the variables. Please help I've been searching all day for a way to use the variables with this update query.
Thanks,
Stacy
You are probably looking for how to use parameters in ADO.NET. For your example, it can look like this:
cmd.Parameters.Add("#zamnt", zamnt);
cmd.Parameters.Add("#zcomp", zcomp);
Put these two lines anywhere before ExecuteNonQuery.
Because parameters need a # prefix, you would also need to change your query to say #zamnt instead of just zamnt, and same for zcomp:
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
In addition to using parameters, the "Using" statement closes the connection and disposes resources:
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Try
Using con As New SqlConnection("Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True")
con.Open()
Using cmd As New SqlCommand
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
cmd.Parameters.AddWithValue("#zamt", zamnt)
cmd.Parameters.AddWithValue("#zcomp", zcomp)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
have u tried this?
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] -" + zamnt + " WHERE [ComponentID] =" + zcomp
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try