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()
Related
I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:
Dim strSql As String = " SELECT * FROM Table_Master WHERE field & "'= ('" & txtCadena.Text & "')"
What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.
Maybe something like:
strSql As String = string.format("SELECT * FROM Table_Master WHERE [{0}] = '{1}'", txtField.text, txtFieldValue.text.replace("'","''"))
This should work (only for text, not dates, numbers etc) but you have to know that it is not the best practice.
I finally made it doing this.
Dim Query As String
Dimm DT As DataTable = New DataTable
Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"
Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)
lblInventory.Text = DT.Rows(0)("Actual").ToString
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.
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?
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.
what i got:
two mdb databases and one application to insert information (rows) from db1 to db2.
when i'am runing my code there is an exception:
System resource exceeded.
the code:
Connection Strings:
Dim db2Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db2.mdb;Persist Security Info=False;")
Dim db1Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\db1.mdb;Persist Security Info=False;")
Code to copy the information:
Dim DataAddapter As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
'Open DB1 Connection:
db1Connection.open()
'Select All From M
DataAddapter.SelectCommand = New OleDb.OleDbCommand("SELECT * FROM M", db1Connection)
Dim cmd As OleDb.OleDbCommand = DataAddapter.SelectCommand
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader()
'Before Reading Results From DB1 Lets Open DB2Connection:
db2Connection.open()
'Start Reading Results in LOOP:
Do Until Reader.Read() = False
Dim F_Name As String = Reader("F_NAME")
Dim L_Name As String = Reader("L_NAME")
Dim CITY As String = Reader("NAME_CITY")
F_Name = Replace(F_Name, "'", "")
L_Name = Replace(L_Name, "'", "")
'Start Moving The Results To Db2(Insert):
'--------------------------------------
Dim Exist As Integer = 0
Dim c As New OleDb.OleDbCommand
c.Connection = db2Connection
c.CommandText = "SELECT COUNT(*) FROM `Names` WHERE `LastName`='" & L_Name & "' AND `FirstName`='" & F_Name & "' AND `City`='" & CITY & "'"
'----------------------------------------
'Exception Here!! :(
'This Line Checking If Already Exist
Exist = CLng(c.ExecuteScalar())
'----------------------------------------
If Exist = 0 Then
c.CommandText = "INSERT INTO `Names` (`LastName`,`FirstName`,`City`) VALUES ('" & L_Name & "','" & F_Name & "','" & CITY & "')"
c.ExecuteNonQuery()
'Note: After this line i'am getting the Exception there... (2 queries executed ExecuteScalar + ExecuteNonQuery) maybe i need to create connection for every query? :S
End If
Loop
another thing:
i have to send the query to db2 in this syntax(Otherwise it does not work):
INSERT INTO `Names` (`LastName`,`FirstName`,`City`) VALUES ('" & L_Name & "','" & F_Name & "','" & CITY & "')
i have to use the -> ` <- to the name of the columns,
but when i'am sending a query to db1 without -> ` <- it's working. :S and i dont know what is the difference between db1 to db2 but its very strange maybe my problem is there...
good answer is a good example plus good explanation :).(c# or vb.net)
You are prime for sql-injection... You should read-up on that, and at a minimum, PARAMETERIZE your sql commands, do NOT build string statement to execute with embedded values. I don't specifically know how db2 handles parameters... some use "?" as place-holders, SQL-Server uses "#" and Advantage Database uses ":".. but in either case, here is the principle of it...
c.CommandText = "select blah from `names` where LastName = ? and FirstName = ? and City = ?"
c.CommandText = "select blah from `names` where LastName = #parmLastName and FirstName = #parmFirstName and City = #parmCity"
For the named parameters above (such as #parmLastName), I am prefixing with "parm" for sole purpose of differentiating a value vs the actual COLUMN name
Then, your parameters would be something like
c.Parameters.Add( "#parmLastName", yourLastNameVariable )
c.Parameters.Add( "#parmFirstName", yourFirstNameVariable)
c.Parameters.Add( "#parmCity", yourCityVariable)
If using the "?" version of parameters where they are not explicitly named, you need to just make sure your parameter context is in the same sequence as the "?" place-holders.
Then execute your call... Same principle would apply for all your queries (select, insert, update, delete)
As for your system resources... how many records are you pulling down. It could just be choking your system memory resources trying to pull down the entire database table. You might want to break down based on one alphabetic letter at a time...
Also, a link from MS about system resources and Access via a patch.