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

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?

Related

visual basic like error

Private Sub txtmid_Change()
On Error Resume Next
Mmid = txtmid.Text
Adodc1.RecordSource = "select * from members where txtmid like '" & Mmid & "'"
Adodc1.Refresh
Mname = Adodc1.Recordset.Fields("Mname").Value
Expiryd = Adodc1.Recordset.Fields("Expiryd").Value
txtname.Text = Mname
txtedate(1).Text = Format(Expiryd, "dd / mm / yyyy")
End Sub
I am getting FROM clause error. Please help me to resolve this error. Thank you.
Try this:
First of all, remove On Error Resume Next, because it's dangerous (you should use a very error handler, instead).
Adodc1.RecordSource = "select * from members where Mmid = '" & Mmid & "'"
Note: anyway, for fields of TEXT type, you should use always Replace$() to 'double quote' to avoid mistake when string values contains a single quote. Example:
Dim sql As String
Dim sSearch As String
sSearch = "You are 'magic' developer"
sql = "SELECT * FROM Users WHERE Note = '" & Replace$(sSearch, "'", "''") & "'"
Otherwise, in this case, if you use (wrongly):
sql = "SELECT * FROM Users WHERE Note = '" & sSearch & "'"
You will get a error.

Represent field in DB by variable

I have a project which is linked with a MDB file. I need to filter records of a table based on a condition, and both "field name" and the value or conditions should be passed to a Sub via variables. The select statement doesn't work. Did I miss something?
Dim Result() As DataRow
Dim strField As String = "asset_code"
Dim dblValue As Double = 3
Dim tblName as Datatable = AssetsDataSet.Assets
Result = tblName.Select(" '" & strField & "' = '" & dblValue& "' ")
I suspect that you need to loose the single quotes around the field name and as the data because it looks like it is numeric:
Result = tblName.Select(strField & " = " & cstr(dblValue) )
With string data you need to use a function:
Result = tblName.Select("textfield = " & cSQL(StringData) )
Function cSQL(psTextData As String) As String
' Replace any single quotes to be 2 single quotes
Return "'" + Replace(psTextData, "'", "''") + "'"
End Function

Sql query to update new values to column Visual Basic

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.

VB.NET: convert text with single quote to upload to Oralce DB

I have a function in VB.NET that runs a query from an MS SQL DB, puts the results into temporary variables, then updates an Oracle DB. My question is, if the string in the MS SQL contains a single quote ( ' ), how do I update the Oracle DB for something that has that single quote?
For example: Jim's request
Will produce the following error: ORA-01756: quoted string not properly terminated
The ueio_tmpALM_Comments (coming from MS SQL) is the culprit that may or may not contain the single quote.
update_oracle =
"update Schema.Table set ISSUE_ADDED_TO_ALM = '1'," & _
"ISSUE_COMMENTS = '" & ueio_tmpALM_Comments & "'," & _
"where ISSUE_SUMMARY = '" & ueio_tmpALM_Summary & "' "
Dim or_cmd_2 = New NetOracle.OracleCommand(update_oracle, OracleConn)
or_cmd_2.ExecuteNonQuery()
From your question it's clear that you are building the update query using string concatenation.
Something like this
Dim myStringVar as string = "Jim's request"
Dim sqlText as String = "UPDATE MYTABLE SET MYNAME = '" + myStringVar + "' WHERE ID = 1"
this is a cardinal sin in the SQL world. Your code will fail for the single quote problem, but the most important thing is that this code is subject to Sql Injection Attacks.
You should change to something like this
Dim cmd As OraclCommand = new OracleCommand()
cmd.Connection = GetConnection()
cmd.CommandText = "UPDATE MYTABLE SET MYNAME = :myName WHERE ID = 1"
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(":myName", myStringVar)
cmd.ExecuteNonQuery()

ORA-01704: string literal too long when updating a record

I am trying to update an Oracle Database record and i keep getting this error:
ORA-01704: string literal too long 5
I looked up that error and it seems that i have a limit of 4000 charters since i am using Oracle 10g. However, the prgblem is that its the same exact data i am putting back into that record so that is why i am unsure as to why its giving me that error for the same amount of data i took out of it.
Here is my update code:
Dim myCommand As New OracleCommand()
Dim ra As Integer
Try
myCommand = New OracleCommand("Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = '" & theData & "' WHERE EID = '81062144'", OracleConnection)
ra = myCommand.ExecuteNonQuery()
OracleConnection.Close()
Catch
MsgBox("ERROR" & Err.Description & " " & Err.Number)
End Try
I'm not sure if there is anything special you have to do in order to update a clob or not.
I extract the clob like so:
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
And it works just fine extracting but just not putting it back in.
Any help would be great!
David
UPDATE CODE
Dim OracleCommand As New OracleCommand()
Dim myCommand As New OracleCommand()
Dim ra As Integer
While dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
theData = Replace(theData, "…", " ")
Try
Dim strSQL As String
isConnected2 = connectToOracleDB2()
OracleConnection.Close()
If isConnected2 = False Then
MsgBox("ERRORConn: " & Err.Description & " " & Err.Number)
Else
myCommand.Connection = OracleConnection2
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'ERROR', COMPLETE_DATE = '', DATA = :1 WHERE EID = '" & theEID & "'"
myCommand.CommandText = strSQL
Dim param As OracleParameter = myCommand.Parameters.Add("", OracleDbType.Clob)
param.Direction = ParameterDirection.Input
param.Value = theData
Application.DoEvents()
ra = myCommand.ExecuteNonQuery()
Application.DoEvents()
OracleConnection2.Close()
Application.DoEvents()
End If
Catch
MsgBox("ERROR: " & Err.Description & " " & Err.Number)
OracleConnection2.Close()
End Try
End While
dr.Close()
OracleConnection.Close()
Do not hardcode the value into your SQL query. Instead wrap it in a parameter. Like this:
Dim strSQL As String
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = :1 WHERE EID = '81062144'"
myCommand.CommandText=strSQL
And then:
Dim param As OracleParameter=myCommand.Parameters.Add("",OracleDbType.Clob)
param.Direction=ParameterDirection.Input
param.Value=blob.Value
You can (and should) of course add all other variables (status code, complete date, eid) of your query as parameters, too, instead of hard-coding them into your SQL.
Varchar2 in sql has a limitations of 4000 characters. This limitation does not apply to the data stored in a varchar column. You need to convert this to pl\sql or specify some other column type. ( I am not a php expert. So I cannot provide any sample, just the reason for your error).
Essentially you need to specify the data type as clob while executing the bind query. Otherwise it will default to varchar2 and the above limitation will apply.