SQL Update with where clause with variables from VS2010 Winforms - vb.net

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

Related

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

vb.net Inserting data to access database

I have the following code to input data into my Access database, but I am getting the following error.
Query input must contain at least one table or query.
What am I doing wrong? Here is the section of code that they is mentioning the lines.
Private Sub EditAddButton_Click(sender As Object, e As EventArgs) Handles EditAddButton.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*******************;Jet OLEDB:Database Password=************;")
Dim insertsql As String
Try
insertsql = "INSERT INTO RepairOrders" & _
"(ROOtherInfo, ROJobType, ROJobTime, RODelPicDate, RONo)" & _
"VALUES (#other, #type, #time, #delpic, #jobno) WHERE ROJobNo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have replaced certain information with asterixs' to cover some sensitive information.
EDIT:
Now I am getting a syntax error :(
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*********************************;Jet OLEDB:Database Password=***********;")
Dim insertsql As String
Try
insertsql = "UPDATE RepairOrders SET ROOther = #other, SET RONo = #jobno, SET ROJobType = #type, SET ROJobTime = #time, SET RODelPicDate = #delpic WHERE RONo = #jobno"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#type", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("#time", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("#delpic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#jobno", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
It looks like you have too many SET statements, and OleDb requires '?' for parameters, and you must take care about the amount of them, and the order they are specified. This is a bit cleaned up, take a look at OLEDB Parameterized Query for a more thorough example.
Try
insertsql = "UPDATE RepairOrders
SET ROOther = ?
, RONo = ?
, ROJobType = ?
, SET ROJobTime = ?
, SET RODelPicDate = ?
WHERE RONo = ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("?", AddOtherText.Text)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
cmd.Parameters.AddWithValue("?", AddTypeCombo.Text)
cmd.Parameters.AddWithValue("?", AddTimeCombo.Text)
cmd.Parameters.AddWithValue("?", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("?", AddJobText.Text)
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

VB.NET: SQL Parameters (Update)

I'm trying to update some values but it seems that there is a problem with my code.
Dim con As New OleDbConnection
Dim id As Integer = Main.Passes.Items.Count + 1
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ...\database.mdb"
con.Open()
Catch ex As Exception
MsgBox("There was a problem connection to database.", MsgBoxStyle.Critical)
End Try
Dim objCmd As OleDbCommand
Dim strSQL As String
strSQL = "UPDATE passwords SET website= #website, username= #username, password= #password, dates= #datenow, notes= #notes WHERE id= #id"
objCmd = New System.Data.OleDb.OleDbCommand(strSQL, con)
objCmd.Parameters.AddWithValue("#website", txtURL.Text)
objCmd.Parameters.AddWithValue("#username", txtUser.Text)
objCmd.Parameters.AddWithValue("#password", txtPass.Text)
objCmd.Parameters.AddWithValue("#datenow", txtDate.Text)
objCmd.Parameters.AddWithValue("#notes", txtNotes.Text)
objCmd.Parameters.AddWithValue("#id", id)
objCmd.ExecuteNonQuery()
con.Close()
The error I get is: Syntax error in UPDATE statement.
Try enclose your column names in `` (backticks). I guess password column is the culprit, probably a keyword.

Sql Adapter . How to update a DataTable with no primary keys

This table that I have has been created with no primary keys. There is a reason why its been created with no keys. It is something like a product and customer relationship table. So after the standard procedure of using SqlDataAdapter and DataSet along with DataTable to fill the DataGrid I have an error updating the changes.
I have been working on several forms using DataGrid' but they all work fine due to the fact the table have primary keys. I tried adding a composite key but it didn't work. So below is my code for theDataSet` and the update code which works for other forms.
The update codes:
cmdbuilder = New SqlCommandBuilder(adapter)
If primaryDS IsNot Nothing Then
primaryDS.GetChanges()
'update changes
adapter.Update(primaryDS)
MsgBox("Changes Done")
'refresh the grid
CMDrefresh()
End If
And here is the coding for the DataTable I tried adding 5 composite keys. So how do you update with this problem?
Try
myconnection = New SqlConnection(strConnection)
myconnection.Open()
adapter = New SqlDataAdapter(StrQuery, myconnection)
adoPrimaryRS = New DataSet
adapter.Fill(primaryDS)
Dim mainTable As DataTable = primaryDS.Tables(0)
DataGrid.AutoGenerateColumns = False
mainTable.PrimaryKey = New DataColumn() {mainTable.Columns(0), _
mainTable.Columns(1), _
mainTable.Columns(2), _
mainTable.Columns(3), _
mainTable.Columns(4)}
bndSrc.DataSource = mainTable
DataGrid.DataSource = bndSrc
gDB.Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
So I decided to go on and answer my question. You cant use the code above to up but you can still insert the new rows. Since Dataset is a memory if the whole database was removed it would not be effect. So the answer to how to update a table with no primary key or composite keys it to trancute it then insert all rows from the Dataset Table in to it. Here is the Code for Trancute and The one below is to insert. With these the table gets new values. It works for me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = strConnection
Dim strSql As String
'MsgBox(con.ConnectionString.ToString)
Try
con.Open()
cmd = New SqlCommand
cmd.Connection = con
strSql = "TRUNCATE TABLE Table1"
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So here is The Insert code.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim strSql As String
con.ConnectionString = strConnection
For i As Integer = 0 To grdDataGrid.Rows.Count - 1
'MsgBox(con.ConnectionString.ToString)
con.Open()
cmd = New SqlCommand
cmd.Connection = con
Try
strSql = "INSERT INTO Table1 ( [one], [two], [three], [four], [five] )" +_
"VALUES (#one, #two, #three ,#four ,#five )"
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("#one", grdDataGrid.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#two", grdDataGrid.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("#three", grdDataGrid.Rows(i).Cells(1).Value)
cmd.Parameters.AddWithValue("#four", grdDataGrid.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#five", grdDataGrid.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
CMDrefresh()

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