Update database in vb.net causing syntax error - vb.net

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()

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

insert or update with single button in vb.net

how to insert and update data in database(sql server) with single button in vb.net i tried but not get the result.
here is my code.......
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim reader As SqlDataReader
Dim query As String
Dim n As Integer
n = 0
sqlcom1 = New SqlCommand("select * from mydatabase.masters")
sqlcom1.ExecuteReader()
sqlcom = New SqlCommand("select * from mydatabase.masters")
sqlcom.ExecuteReader()
reader = sqlcom1.ExecuteReader
reader = sqlcom.ExecuteReader
sqlcom = New SqlCommand("Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid", conn)
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = TextBox3.Text
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
sqlcom.Parameters.Add("#Empid", SqlDbType.Int).Value = TextBox1.Text
sqlcom1 = New SqlCommand("insert into masters(Empid, EmpName, Age, Address) values(#Empid, #EmpName, #Age, #Address)", conn)
sqlcom1.Parameters.AddWithValue("#Empid", TextBox1.Text)
sqlcom1.Parameters.AddWithValue("#EmpName", TextBox4.Text)
sqlcom1.Parameters.AddWithValue("#Age", TextBox3.Text)
sqlcom1.Parameters.AddWithValue("#Address", TextBox2.Text)
conn.Open()
While reader.Read
n = n + 1
End While
If table.Rows.Count = n Then
sqlcom1.ExecuteNonQuery()
ElseIf table.Rows.Count = n + 1 Then
sqlcom.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
Using block ensures that your connection object is closed and disposed even if there is an error.
Normally I put comments in line but the code got so cluttered that had to move most of them up here. I hope you can figure out where they belong.
Dim reader As SqlDataReader - Unused
Dim query As String - Unused
Integers are automatically initialized to zero
Pass the query and the connection to the constructor of the command.
Your connection string will tell SQL Server what database to use. It is not necessary in the query.
Apparently all you want is the count, not all the data.
This query is exactly the same as sqlcom1
Dim sqlcom As New SqlCommand("select * from mydatabase.masters", cn)
sqlcom.ExecuteReader()
You did this twice
reader = sqlcom1.ExecuteReader
Not necessay, we already retrieved the count
`While reader.Read
n = n + 1
End While`
I made the assumption that table was a DataTable populated at some other time. Using the count as comparison to the count in the table is not a great way to determine if the command is Insert or Update but it might work as long as database and table were not used with a DataAdapter that updated the database.
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim n As Integer
Using cn As New SqlConnection("Your connection string")
Dim sqlcom1 As New SqlCommand("select Count(*) from masters", cn)
cn.Open()
n = CInt(sqlcom1.ExecuteScalar) 'n is now the number of rows in the database table
Dim sqlcom As New SqlCommand
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
'Age is not a good idea to enter in a database. It changes over time.
'Enter the birth date and calculate the age as needed.
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = CInt(TextBox3.Text)
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
If table.Rows.Count > n Then
'Normally EmpId would be an auto increment (identity) field
'and would NOT be included in an insert.
sqlcom.CommandText = "insert into masters(EmpName, Age, Address) values(#EmpName, #Age, #Address)"
Else
sqlcom.CommandText = "Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid"
sqlcom1.Parameters.Add("#Empid", SqlDbType.Int).Value = CInt(TextBox1.Text)
End If
sqlcom.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
On second thought, forget the whole thing. Use a DataGridView and a DataAdapter. Then you can just use Update and it will update, insert and delete.

How to delete row from both Datagridview and the record from the table

In my datagridview, you can select a row, and upon pressing a button, the content of two of the four fields is transported to another table. At this point, the row selected in my datagridview should be deleted from both the datagridview and the table it's reading from. Currently I am able to take the two fields I need and put them into the other table, but am having difficulty deleting this record after.
This is my code:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\..\RailwayDatabase2.accdb"
Dim Con As OleDb.OleDbConnection
Dim comm As OleDbCommand
Dim rowval As Integer
Dim connect, query As String
Try
rowval = RotorDGV.CurrentCell.RowIndex
Catch ex As Exception
End Try
Dim col1 As String
Dim col3 As Date
col1 = RotorDGV.Rows(rowval).Cells(1).Value
col3 = RotorDGV.Rows(rowval).Cells(3).Value
connect = "provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\..\RailwayDatabase2.accdb"
query = "INSERT INTO tbl_shifts (EmployeeName, ShiftDate) VALUES(""" & col1 & """,""" & col3 & """);"
Con = New OleDb.OleDbConnection(connect)
comm = New OleDb.OleDbCommand(query, Con)
Con.Open()
comm.ExecuteNonQuery()
The row I need deleted currently equals RotorDGV.CurrentCell.RowIndex or 'Rowval'.
Can someone please tell me how to erase this record from both the table and datagridview upon clicking this button. Thank you
After you do the insert statement and execute the query.
Repeat the process for delete staement and execute the query again.And then remove a row from the datagridview.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\..\RailwayDatabase2.accdb"
Dim Con As OleDb.OleDbConnection
Dim comm As OleDbCommand
Dim rowval As Integer
Dim connect, query As String
Dim col1 As String
Dim col3 As Date
Private Sub RotorDGV_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles RotorDGV.CellClick
Try
rowval= DataGridView1.CurrentCell.RowIndex
Catch ex As Exception
End Try
End Sub
In the button click event, do the following all code.
Insert statement
col1 = RotorDGV.Rows(rowval).Cells(1).Value
col3 = RotorDGV.Rows(rowval).Cells(3).Value
query = "INSERT INTO tbl_shifts (EmployeeName, ShiftDate) VALUES(""" & col1 & """,""" & col3 & """);"
Con = New OleDb.OleDbConnection(connString)
comm = New OleDb.OleDbCommand(query, Con)
Try
Con.Open()
comm.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Con.Close()
End Try
Delete statement
query = "DELETE STAEMENT"
Con = New OleDb.OleDbConnection(connString)
comm = New OleDb.OleDbCommand(query, Con)
Try
Con.Open()
comm.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Con.Close()
End Try
Remove row from Datagridview
RotorDGV.Rows.RemoveAt(rowval)
Hope it helps or at least you get a hint.
Can you run a stored procedure to delete ? I would pass in the parameters needed to delete the record.

transaction in ms access and 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.

VB.Net Update doesn't update my database

This is the code that I am trying to run. It will run without errors, but it does not update my database.
It will work when it is not Parameterized, but when I add parameters in it starts acting up. Here is the problematic code.
Public Sub updateItem()
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
cmd.CommandText = "Update Inventory set PartNumber='#PartNumber', Brand='#Brand', PartDescription='#PartDescription', PartCost=#PartCost, InventoryOnHand=#InventoryOnHand, PartSupplier='#PartSupplier' where PartNumber = '#PartNumMatch' and Brand = '#PartManMatch';"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
'SQl statement to try to update the selected row's data matched against the database.
'update listview here.
End Sub
I am almost sure that the syntax is correct because my insert works. Here is the code to my insert.
Private Sub addItem()
'SQL statement here to add the item into the database, if successful, move the information entered to listview.
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
'Dim reader As SqlDataReader
cmd.CommandText = "Insert into Inventory ([PartNumber], [Brand], [PartDescription], [PartCost], [InventoryOnHand], [PartSupplier]) values (#PartNumber, #Brand, #PartDescription, #PartCost, #InventoryOnHand, #PartSupplier);"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text().Trim())
cmd.Parameters.AddWithValue("#PartCost", partCostText.Text())
cmd.Parameters.AddWithValue("#InventoryOnHand", quantityText.Text())
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Dim found As Boolean = False
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
MessageBox.Show(cmd.CommandText)
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
End Sub
I know that the where clause is right, I have hard-coded the value's and I have also pushed the value's being compared to message box's and compared them directly to the information in the database.
Thanks in advance for any and all opinions and I hope we can get it figured out.
The parameters placeholders should not be enclosed in single quotes
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
You don't need to do that, it only confuses the code that tries to replace the parameter placeholder with the actual value. They will be treated as literal strings
Try this,
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())