transaction in ms access and vb.net - vb.net

I am trying the below code but not getting executed.
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
cmd.Transaction = tra
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment) values('" + txtcategory.Text + "','" + txtcomment.Text + "')"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 WHERE (cname = txtcategory.Text)"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
Try : tra.Rollback() : Catch : End Try
End Try
End Using
End Sub
I don't understand the transactions.

The command need to know about the existence of a Transaction. But you assign the Transaction instance before the opening the connection and then ask the connection to start the transaction.
In this way the command has a null reference for the transaction and not the good instance created by the connection. Also, when you create again the command, there is no transaction associated with it.
Better use the OleDbCommand constructor that takes a Transaction as third parameter
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment)" &
" values(#cat, #com)"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#cat", OleDbType.VarWChar).Value = txtcategory.Text
cmd.Parameters.Add("#com", OleDbType.VarWChar).Value = txtcomment.Text
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 " &
"WHERE cname = #cat"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#car", OleDbType.VarWChar).Value = txtcategory.Text
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
tra.Rollback()
End Try
End Using
End
I have also changed your code to use a more safe approach to your queries. Instead of using a string concatenation use ALWAYS a parameterized query. In this way you are safe from Sql Injection, you don't have problems with parsing texts and your queries are more readable.

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. Here's my code:
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
Try
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
con.Open()
MsgBox("Connection Open ! ")
cmd.ExecuteNonQuery()
MsgBox("Record inserted")
con.Close()
Catch ex As Exception
MsgBox("Error!")
End Try
End Sub
For future readers - Sql parameters will save a lot of your and your coworkers time.
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim connString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;"
Using connection As New SqlConnection(connString)
Using command As New SqlCommand(connection)
command.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (#FirstName, #Lastname)"
Dim params As SqlParameter() =
{
New SqlParameter With { .ParameterName = "#FirstName", .SqlDbType.VarChar, .Value = txtFirstName.Text },
New SqlParameter With { .ParameterName = "#LastName", .SqlDbType.VarChar, .Value = txtLastName.Text },
}
command.Parameters.AddRange(params)
connection.Open()
command.ExecuteNonQuery()
' Inserted
End Using
End Using
End Sub
Same for try.. catch(as #Plutonix has noticed in the comments) - if you will get "real" exception you will find reason and solution much faster
You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test.
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"
Check out parameterized query as previously indicated

Update database in vb.net causing syntax error

I am trying to update a database record when a user amends it. I have a textbox called 'txtColsTextBox' which stores the value and a button called 'btnSaveExit'. On the button click, I need to update the db with new value.
How would I do this based on my code. I am thinking , i need to use me.validate function but not sure how to code. Thanks
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String
connetionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\storage.accdb"
sql = "SELECT Cols FROM Racks Where [Rack code] = '" & buttonName & "'"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While oledbReader.Read
'MsgBox(oledbReader.Item(0))
txtColsTextBox.Text = oledbReader.Item(0)
End While
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
EDIT: Code to Update db
Private Sub btnSaveExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveExit.Click
Try
connetionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\storage.accdb"
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
oledbCmd.CommandText = "UPDATE [Racks] SET [Cols] VALUES (?)"
oledbCmd.Parameters.AddWithValue("#Cols", txtColsTextBox.Text)
oledbCmd.ExecuteNonQuery()
MessageBox.Show("Record succesfully updated" + txtColsTextBox.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Change your UPDATE statement to the following form:
UPDATE [Racks] SET [Col1] = ?, [Col2] = ? WHERE [IdCol] = ?
The sample assumes that you want to update Col1 and Col2 with new values and only for one record (the one where IdCol equals the id). Add the parameters in an order that corresponds to the order in the UPDATE statement.
To show you were to start, you can use something like this (adjust tablename, fieldnames, and parameters)
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
oledbCmd.CommandText = "INSERT INTO [TableName] ([Fieldname1], [Fieldname2]) VALUES (?,?)"
oledbCmd.Parameters.Add( .... )
oledbCmd.Parameters.Add( .... )
oledbCmd.ExecuteNonQuery()

how to simplify codes

I have a next button.
theres no error i just want to simplify
Try
lblcat.Text = ds.Tables("evaluation").Rows(cat)("QuestionCategory")
txt1.Text = ds.Tables("evaluation").Rows(CurrentRow)("Question")
txt2.Text = ds.Tables("evaluation").Rows(CurrentRow + 1)("Question")
txt3.Text = ds.Tables("evaluation").Rows(CurrentRow + 2)("Question")
txt4.Text = ds.Tables("evaluation").Rows(CurrentRow + 3)("Question")
txt5.Text = ds.Tables("evaluation").Rows(CurrentRow + 4)("Question")
Catch ex As Exception
End Try
every click to the next button my category and questions change.
every click i want also to save in my database
Private Sub Save_commit()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
'I just use the textbox tag property to idetify if the data is new or existing.
sSQL = "INSERT INTO evaluationresult ([Com])" & _
" VALUES (?)"
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#FacultyID", txtresult.Text)
'cmd.Parameters.AddWithValue("#IDNumber", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Com", OleDbType.Numeric).Value
' cmd.Parameters.AddWithValue("#Know", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Teaching", OleDbType.Numeric).Value
'cmd.Parameters.Addwithvallue("#man", OleDbType.Numeric).Value()
'cmd.Parameters.AddWithValue("#ID", OleDbType.Numeric).Value
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ErrorToString)
Finally
con.Close()
End Try
End Sub
please improve

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