Sql query to update new values to column Visual Basic - vba

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.

Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.

Related

Solve error in update query

I have code that throws an error - I need your help to solve it.
The error is
Syntax error in update statement
My code:
Try
Dim conn As OleDbConnection = New OleDbConnection(My.Resources.ConnectionString)
Dim cmd As OleDbCommand
conn.Open()
Dim Sql As String = "select * from Administretor"
cmd = New OleDbCommand(Sql, conn)
Dim userE, userR As String
userE = txtOldPass.Text
Dim reder As OleDbDataReader = cmd.ExecuteReader()
While reder.Read()
userR = reder.Item(0)
End While
If userE = userR Then
If txtNewPass.Text = txtNewConfromPass.Text And txtNewConfromPass.Text <> "" And txtNewPass.Text <> "" Then
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Dim cmd0 As OleDbCommand = New OleDbCommand(Sql, conn)
cmd0.ExecuteNonQuery()
Else
MsgBox("Make sure that you have entered new password in both text Box and they both are same...!")
End If
Else
MsgBox("Enter the correct Username")
End If
MsgBox("Done 2")
Catch ex As OleDbException
MsgBox(ex.Message)
End Try
Two errors
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
Missing single quote here---+ |
|
LogIn_Id will never equal the old password--------------------------------+
But apart from the simple syntax errors you have a huge SQL injection vulnerability from building the SQL out of pieces including user input.
In this part,
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where ...
The PASSWORD will have a single quote before it, and no single quote after it.
Change it to:
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & "' where ...
Notice the extra single quote here ----------------------------------------^
Add this syntax :
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Clipboard.SetText(Sql)
The query will be in your clipboard. Run it on SQL(whichever you are using), and see if the query runs smoothly?
Please show us what the query generation holds and what the error it produce when running directly from the SQL.

Receiving an error when attempting to update a record

In my program I have a function titled runSQL, here it is:
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TrainingLog.accdb")
Dim DT As New DataTable
Dim DataAdapter As OleDb.OleDbDataAdapter
Connection.Open()
DataAdapter = New OleDb.OleDbDataAdapter(query, Connection)
DT.Clear()
DataAdapter.Fill(DT)
Connection.Close()
Return DT
And I'm trying to update a record in a database using the update string, sourced from this code:
Dim sqlString As String
sqlString = "UPDATE UserRecords set FirstName = '" & txtName.Text
sqlString = sqlString & "', LastName = '" & txtSurname.Text
If ChkSmoker.Checked = True Then
sqlString = sqlString & "', Smoker = true"
ElseIf ChkSmoker.Checked = False Then
sqlString = sqlString & "', Smoker = false"
End If
sqlString = sqlString & ", Weight = " & txtWeight.Text
If RdoMale.Checked = True Then
sqlString = sqlString & ", Gender = 'm'"
ElseIf RdoFemale.Checked = True Then
sqlString = sqlString & ", Gender = 'f'"
End If
sqlString = sqlString & " WHERE UserName = '" & LstUsers.SelectedItem.ToString & "'"
runSQL(sqlString)
However once I click the save button, I get an error from line 7 of the runSQL function (not including empty line, so that's the DataAdapter.Fill(DT) line) which says "No value given for one or more required parameters."
I wondered if anyone knew why this is or how to fix it.
One thing I did think of is that, in the table being updated, there are fields other than those being mentioned in my UPDATE statement. For example there is a Yes/no field titled "TeamMember", which I don't mention in the update statement.
When using the update function, do I have to give values for every field, even those not being changed?
Thanks for reading, and hopefully helping!
You should never composea SQL query yourself. It much easies and safer (to vaoid SQL injection) to create a parameterized query, or use an stored procedure. And then execute it by pasing the query or stored procedure name and the parameter values.
Besides, in this way, you don't have to take care of what the right format is for a particular value. For example, how do you format a date? And, how do you format a boolean value? Most probably the problem with your query is the false or true value that you're trying to set for the Smoker column, because in TSQL that's a bit value, and can only be 0 or 1.
Check this to see samples of using parameters: ADO.NET Code Examples (Click the VB tab to see it in VB). You'll see that you define a parameter specifying a name with an # prefix in the query, and then you simply pass a value for each parameter in the query, and it will be passed to the server in the correct format without you taking care of it.
Taken from one of the samples:
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > #pricePoint " _
& "ORDER BY UnitPrice DESC;"
Dim command As New SqlCommand(queryString, connection)
command.Parameters.AddWithValue("#pricePoint", paramValue)
'' command.ExecuteXXX
NOTE that you can execute the command in different ways, depending on your need to simply execute it or get an scalar value or a full dataset as a result.

Incorrect syntax near 's'. Unclosed quotation mark after the character string

I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?

execute multiple command for update vb.net

i am working on a vb project . in this i need to save some record to one table and update some records in another table in one event or click .. i am doing like this .
dim simpan as new sqlcommand
conn = New SqlConnection(connectionstring)
conn.Open()
simpan = New SqlCommand()
simpan.Connection = conn
simpan.CommandType = CommandType.Text
simpan.CommandText = "update barang set (nama_barang,harga)values(" & TextBox3.Text & ",'" & TextBox4.Text & "') where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()
tampil()
MsgBox("Data Berhasil Diubah", MsgBoxStyle.Information, "Informasi")
conn.Close()
but it giving error as "incorrect syntax near '('" .. i am not getting where i go wrong .. please help me
I see a couple issues with this...
Your Syntax is wrong on your update statement (Al-3sli beat me to that one).
Your textbox values will cause issues if a user types a single quote in the text box (For Example: The word "Wasn't".
Add the replace function to each textbox TextBox3.text.Replace("'","''") That will replace single ticks with two single ticks.
You might also consider using parameterized queries
You can't use update like this, change your code like so:
simpan.CommandText = "update barang set nama_barang = '" & TextBox3.Text & "',harga ='" & TextBox4.Text & "' where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()

Preventing escaping apostrophes with parameter query not working

I am trying to prevent from having to escape apostrophes in my string variables by using a parameterized query with a SqlConnection, but it is not working. any help would be appreciated.
UPDATED: this is current code...
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text) ; "
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Try
Dim results As Integer = oCmd.ExecuteScalar
Catch ex As Exception
LabelImport.Text &= "<font color=red>ROOT Import ERROR: " & ex.ToString & ", From Database: " & dbName & ", Text String: " & data_text & "</font><br />"
Throw
End Try
oCnn.Close()
oCmd.Parameters.Clear()
Thanks for any help.
Yeah, that's not right.
It should look like this:
Dim sSQL As String = "INSERT INTO [" & foreignTable & "] (data_text) VALUES (#data_text);"
and for the parameter:
oCmd.Parameters.AddWithValue("#data_text", data_text)
Note: I don't "think" you can pass the table name as a parameter. You would have to have the table name in the string. See Parametise table name in .Net/SQL?
Also, change this:
Dim results As Integer = oCmd.ExecuteScalar
to
Dim results as Integer = oCmd.ExecuteNonQuery()
You can use table name only when creating query (I mean concatenating it from parts: "INSERT INTO " + foreignTable + " (data_text) VALUES..., AFAIK), not as query parameter. Check SqlParameterCollection.AddWithValue on MSDN for more information about SqlCommand parameters, there is very good example as well.
'Populate Connection Object
Dim oCnn As New SqlConnection(strConnection)
'Define our sql query
Dim sSQL As String = "INSERT INTO " & foreignTable & " (data_text) VALUES (#data_text);"
'Populate Command Object
Dim oCmd As New SqlCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value
oCmd.Parameters.AddWithValue("#data_text", data_text)
'Opening Connection for our DB operation
oCnn.Open()
Edit:
+ changed to & because of C# as "native language".