Error: Syntax error in UPDATE statement - vb.net

the error i get while executing the code below in OleDb
Try
con.Open()
Dim cmd As New OleDbCommand("Select * from customer", con)
cmd.CommandText = " update customer set hr =#hr,min =#min "
cmd.Parameters.AddWithValue("#hr", ComboBoxHr.SelectedIndex.ToString())
cmd.Parameters.AddWithValue("#min", ComboBoxMin.SelectedIndex.ToString())
cmd.ExecuteNonQuery()
TwoDigit(ComboBoxHr)
MessageBox.Show("CONRATULATIONS! ...Click the Start button to see the changes")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
Which works fine if i remove the "min" part.
What could be the reason?

I believe AakashM is right. You can however use a keyword as a column name as long as you put it in [] like
Try
con.Open()
Dim cmd As New OleDbCommand("Select * from customer", con)
cmd.CommandText = " update customer set hr =#hr,[min] =#min "
cmd.Parameters.AddWithValue("#hr", ComboBoxHr.SelectedIndex.ToString())
cmd.Parameters.AddWithValue("#min", ComboBoxMin.SelectedIndex.ToString())
cmd.ExecuteNonQuery()
TwoDigit(ComboBoxHr)
MessageBox.Show("CONRATULATIONS! ...Click the Start button to see the changes")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try

MIN is a keyword in SQL (it's the aggregate function for finding the minimum of a group of values). Either use a different name for your column, or enclose it in [ square brackets ] - I'm not actually sure if this will work in Access, mind...

Related

I like to delete oracle table multiple records through vb.net datagridview, ora 00936 missing expression error is come for below coding

For Each row As DataGridViewRow In selectedRows
Dim str As String
str = "DELETE from sheet1 WHERE Id = #Id"
Dim cmd As OracleCommand = New OracleCommand(str, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add(New OracleParameter("#Id", row.Cells("Id").Value))
Try
con.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
I like to delete oracle table multiple records through vb.net DataGridView, ora 00936 missing expression error is come for below coding.. if im using AddWithValue instead of cmd.parameter.add then the error is AddWithValue is not a member of oracle.dataAccess.client.oracleparametercollection..
Please help me..
Create the connection and command outside the loop. The only thing that changes inside the loop is the value of the parameter. Open the connection once outside the loop.
CommandType.Text is the default value for .CommandType and doesn't need to explicitly stated.
Use a Using...End Using block to insure that your database objects are closed and disposed even if there is an error.
Notice the parameter name is preceded by a colon in the .CommandText. When the parameter name is provided to the Parameter constructor there is no colon. I have not tested this. This is info from https://learn.microsoft.com/en-us/dotnet/api/system.data.oracleclient.oraclecommand.parameters?view=netframework-4.8 Check the last paragraph in Remarks.
Private Sub OPCode(selectedRows As List(Of DataGridViewRow))
Using con As New OracleConnection("Your connection String"),
cmd As New OracleCommand("DELETE from sheet1 WHERE Id = :Id", con)
'This will bind parameters by name instead of the order they appear in the command text.
cmd.BindByName = True
cmd.Parameters.Add("Id", OracleDbType.Int32)
con.Open()
For Each row As DataGridViewRow In selectedRows
cmd.Parameters("Id").Value = row.Cells("Id").Value))
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
End Using
End Sub

Having trouble understanding the # parameter in a SQL command

Good morning,
I am having trouble understanding the # parameter in vb.net. if we take the example code for the msdn:
' Update the demographics for a store, which is stored
' in an xml column.
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = #demographics " _
& "WHERE CustomerID = #ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
' Use AddWithValue to assign Demographics.
' SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml)
There seem to be no problem at all, however when you try to add more parameters into the mix, it does not seems to work. What would be the correct syntax to add more than one parameter?
Here is my piece of code:
query &= "INSERT INTO "
query &= imageProcAlgo.GetSqlTable()
query &= " ( #dateTimeStampCol , #numberOfBlobsCol , #AvgLengthCol , #avgWidthCol ) "
query &= "Values (#dtsvalue, #nbOfBlobsValue, #avgLengthValue, #avgWidthValue)"
and here where I try to add values to those parameters:
Using conn As New SqlConnection(connectStr)
Using comm As New SqlCommand(query)
With comm
.Connection = conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("#dateTimeStampCol", "DateTimeStamp")
.Parameters.AddWithValue("#numberOfBlobsCol", "NumberOfBlob")
.Parameters.AddWithValue("#AvgLengthCol", "AvgWidth")
.Parameters.AddWithValue("#avgWidthCol", "AvgLength")
.Parameters.AddWithValue("#dtsvalue", "CURRENT_TIMESTAMP")
.Parameters.AddWithValue("#nbOfBlobsValue", imageProcAlgo.GetnumberOfBlobs().ToString())
.Parameters.AddWithValue("#avgLengthValue", imageProcAlgo.GetAvgWidth())
.Parameters.AddWithValue("#avgWidthValue", imageProcAlgo.GetAvgLength())
End With
Try
conn.Open()
comm.ExecuteNonQuery()
conn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
When I try to execute this piece of code, I get an error saying that #datetimestampcol and so on are not valid column names.
I don't seem to understand what is the difference between the MSDN anf my code but i feel pretty close.. Any pointers for me to understand a bit better? to figure out where I went wrong?
Thanks,

Display SQL Result in label?

Dim invoiceCount As String =
"SELECT COUNT(CustomerID) " &
"FROM Invoices " &
"WHERE CustomerID = #customerID"
Dim selectCount As New OleDbCommand(invoiceCount, connection)
selectCount.Parameters.AddWithValue("#customerID", customerID)
Try
connection.Open()
Dim reader2 As OleDbDataReader = selectCount.ExecuteReader(CommandBehavior.SingleRow)
If reader2.Read Then
frmCustomerMaintenance.lblIncidents.Text = 'what do I put here?
End If
reader2.Close()
Catch ex As OleDbException : Throw ex
Finally : connection.Close()
End Try
I've been messing with this for a while now and everything I try returns an error. I'm still fairly new to SQL in general but this needs to be done. I just want to store the result of the query in a label to show how many records the customer entered has..
Well, to read the first column, you can just do this:
frmCustomerMaintenance.lblIncidents.Text = reader.GetValue(0).ToString()
However, when you are only reading a single column from a single row, like that, it's easier to just call ExecuteScalar instead of ExecuteReader:
frmCustomerMaintenance.lblIncidents.Text = selectCount.ExecuteScalar().ToString()
This is what you are searching for:
frmCustomerMaintenance.lblIncidents.Text = reader2[0].ToString()

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

Code does not work but has no errors

I'm working on an information system and here's my syntax for update, it shows no errors, but it does not update my table. Anyone can help on this matter?
By the way, I'm using VB.Net 2010 and MS Access 2007.
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand( "UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
.AddWithValue("#PropertyPropertyID", Val(propertyPayorSessionID.ToString))
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try
You just have a typo on your code
Replace
#PropertyPropertyID
with
#PropertyPayorID
then arrange your parameter order same as your update statement.
And try this :
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand("UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
'.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString)) move this to the last part
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString))
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try
This will solve your problem.
see also: OleDbCommand parameters order and priority for reference.
Best Regards!
If I remember correctly, by default, there is no relation between the name of the place holders in the query and the name of the parameters. As BizApps has said, you should place your parameters in the same order as defined in your query; which means that PropertyPayorID should come last when you add it to your Parameters collection. The names for the Parameters collection are to be used only locally; like for changing some properties of the individual parameters.
Also, I don't remember if you can use named parameters in your query string as a place holder or if you must use a ? instead; something like Update PropertiesPayors SET [PayorName]=?, ...
The command statement .ExecuteNonQuery returns the number of rows which were affected.
This means if you used...
intRowsAffected = .ExecuteNonQuery()
And the value returned into the variable intRowsAffected was ZERO (0)
Then that means a record with the same value for your field PROPERTYID (meaning the value you passed into the parameters collection... PROPERTYPAYORSESSIONID) does not exist!
And thats why you are not recieving any errors and nor is your database being updated.
To double check this...
Where your code statement .EXECUTENONQUERY() is...
You can replace it with the following...
intRowsAffected = .ExecuteNonQuery()
Messagebox(intRowsAffected & " Data rows were updated.")
If the messagebox shows zero rows were updated (no rows were updated) then your next step would be to MANUALLY check the database and see if the row ACTUALLY exists and if it has the SAME key value that you are using to identify the row - which I assume is the property-payor-session-id.
Also keep in mind that the session-id is apt to change with each session and not static all the time.