insert string with " ' " to oracle - sql

Hey I'm using oracle DB with Iron Python and I'm having trouble with strings that contains the char " ' " like in Mc'donalds. (I know it is looking for the closing ' )
The string is accepted from the user input and I want to add it to my DB as it is, meaning without omitting or changing any character.
How can I do it?

Try using the "q" (quote) function:
INSERT INTO restaurantTable (name)
VALUES (q'[O'Reilly and Conway's Irish Pub]');
You can also double-up the single apostrophes (O''Reilly and Conway''s Irish Pub). But in your case you'd have to parse them out, so either using the quote function or query parameters would work the best.
For more information: Q-quote operator introduced in Oracle 10g

Taken from PL/SQL, how to escape single quote in a string?
You can do it either using Q quoting like
q'[insert into MY_TBL (Col) values('ER0002')]';
OR you can use two quotes to denote a single quote
'insert into MY_TBL (Col) values(''ER0002'')';

Related

Can I avoid sql injection in sqlite fts replacing quotes? [duplicate]

I wrote the database schema (only one table so far), and the INSERT statements for that table in one file. Then I created the database as follows:
$ sqlite3 newdatabase.db
SQLite version 3.4.0
Enter ".help" for instructions
sqlite> .read ./schema.sql
SQL error near line 16: near "s": syntax error
Line 16 of my file looks something like this:
INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there\'s');
The problem is the escape character for a single quote. I also tried double escaping the single quote (using \\\' instead of \'), but that didn't work either. What am I doing wrong?
Try doubling up the single quotes (many databases expect it that way), so it would be :
INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
Relevant quote from the documentation:
A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. BLOB literals are string literals containing hexadecimal data and preceded by a single "x" or "X" character. ... A literal value can also be the token "NULL".
I believe you'd want to escape by doubling the single quote:
INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
for replace all (') in your string, use
.replace(/\'/g,"''")
example:
sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")
Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.
String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");
String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";
this works for me in c# and java
In C# you can use the following to replace the single quote with a double quote:
string sample = "St. Mary's";
string escapedSample = sample.Replace("'", "''");
And the output will be:
"St. Mary''s"
And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:
private static string MySqlEscape(Object usString)
{
if (usString is DBNull)
{
return "";
}
string sample = Convert.ToString(usString);
return sample.Replace("'", "''");
}
In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).
In this example, columnA's value could be null or contain hyphens.:
sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";
Demonstration of single quoted string behavior where complexity or double quotes are not desired.
Test:
SELECT replace('SAMY''S','''''','''');
Output:
SAMY'S
SQLite version:
SELECT sqlite_version();
Output:
3.36.0

MSAccess SQL Too few parameters. Expected 4

I'm using Delphi XE2 and AnyDAC and an MSAccess db.
The table 'timea' has 5 fields:
Rec_No AutoNumber
App text
User_ID text
PW text
Comment memo
This code throws the error below. The query works just fine in Access query designer.
sql := 'INSERT INTO [timea] (App, User_ID, PW, Comment) VALUES ("zoo", "Bill", "mi7", "Liger");';
adconnection1.ExecSQL(sql);
Project PWB.exe raised exception class EMSAccessNativeException with message '[AnyDAC][Phys][ODBC][Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 4.'.
Both SQL and Delphi are using single quotes as string boundaries. Since you want to have singe quote inside the string, you have to "escape" it using doube single quote.
For example, if you write S := 'Guns''N''Roses' the varieble S will contain string Guns'N'Roses - 12 characters, not 14.
Be careful when you are concatenating string values, since they might contain single quotes, too. The recommended way to write the query in this case is, for example:
sql := 'INSERT INTO Table (Col) VALUES (' + QuotedStr(Val) + ')';
Function QuotedStr wll take care and double all single quotes in the string. This is also essential to avoid insertion hacks.

Escape sequence character in sql query parameter in windows azure

When querying a string column, if the search parameter has a " ' " in it, the execution fails due to a syntax error. I tried to use an escape sequence character (if thats how its called), but it still does not work.
SELECT * FROM OpusOne.Accounts WHERE firstName like '%jose\'%'
What would be the correct way to add a quote " ' " to a string parameter ?
Thank you
Try this:-
SELECT * FROM OpusOne.Accounts WHERE firstName like '%jose''%'
Escape using another single quote.

Replace quote in SQL Select

I have a scenario in my vb.net project where users need to select a name from a combobox (or type a new name).
Names of course can have ' as in Tina O'Hara which in the database would be stored as Tina O''Hara.
My combobox is populated from a sql select command. I have tried to use a Replace so that the names display correctly in the dropdown.
SqlStr = "SELECT Replace(ContactName, '''', ''') AS ddlText FROM tbl_Visits Where CustID = " & hd_CustID.value & " ORDER By ContactName"
PopulateCMBX(cmbx_ContactName, SqlStr, "Please Select")
PopulateCMBX... This gets a list of names from the supplied SqlStr and populates the combobox itemlist with a 'Please Select' as the first option.
SqlStr is producing an error as there is not a matching set of ' how do I fix this. Thanks
When referencing single quotes in MS-SQL, you need to escape each single quote (') with two single quotes ('').
If the name is stored in the database with two single quotes, such as (''), then when you do the replace you need to use four single quotes (''''). In addition to these, you need to enclose the string with single quotes.
What this means is that your replace should look like this:
SqlStr = "SELECT Replace(ContactName, '''''', '''') ...
The 2nd param in the replace has 6 single quotes: 4 to represent the two single quotes you are replacing, and 2 to make it a string. The 3rd param has 4 single quotes: 2 to represent a single escaped quote and two to make it a string.
Try with this, maybe not the best solution but it works (check this example):
select Replace(Replace(ContactName, '''', '$&'),'$&$&','''') from tbl_Visits
Note that $& is like a key that should not affect the values ​​in your field, for example, could be a word: &&k&& or %%key%%, etc.
Back to clarify, it is not the best solution, but sometimes i've used.

How to enter special characters like "&" in oracle database? [duplicate]

This question already has answers here:
How do I ignore ampersands in a SQL script running from SQL Plus?
(7 answers)
Closed 5 years ago.
I want to insert special character & in my insert statement. My insert is:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.
How can I enter special characters like & in the insert statement for oracle db?
If you are in SQL*Plus or SQL Developer, you want to run
SQL> set define off;
before executing the SQL statement. That turns off the checking for substitution variables.
SET directives like this are instructions for the client tool (SQL*Plus or SQL Developer). They have session scope, so you would have to issue the directive every time you connect (you can put the directive in your client machine's glogin.sql if you want to change the default to have DEFINE set to OFF). There is no risk that you would impact any other user or session in the database.
Try 'Java_22 '||'&'||' Oracle_14'
Justin's answer is the way to go, but also as an FYI you can use the chr() function with the ascii value of the character you want to insert. For this example it would be:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 '||chr(38)||' Oracle_14');
you can simply escape & by following a dot. try this:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');
To Insert values which has got '&' in it. Use the folloiwng code.
Set define off;
Begin
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
End ;
And Press F5 from Oracle or Toad Editors.
There are 3 ways to do so :
1) Simply do SET DEFINE OFF; and then execute the insert stmt.
2) Simply by concatenating reserved word within single quotes and concatenating it.
E.g. Select 'Java_22 ' || '& '|| ':' || ' Oracle_14' from dual --(:) is an optional.
3) By using CHR function along with concatenation.
E.g. Select 'Java_22 ' || chr(38)||' Oracle_14' from dual
Hope this help !!!
We can use another way as well
for example to insert the value with special characters 'Java_22 & Oracle_14' into db we can use the following format..
'Java_22 '||'&'||' Oracle_14'
Though it consider as 3 different tokens we dont have any option as the handling of escape sequence provided in the oracle documentation is incorrect.
If an escape character is to be added at the beginning or the end like "JAVA", then use:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', ''||chr(34)||'JAVA'||chr(34)||'');
For special character set, you need to check UNICODE Charts. After choose your character, you can use sql statement below,
SELECT COMPOSE('do' || UNISTR('\0304' || 'TTTT')) FROM dual;
--
dōTTTT
Also you can use concat like this :D
Insert into Table Value(CONCAT('JAVA ',CONCAT('& ', 'Oracle'));
strAdd=strAdd.replace("&","'||'&'||'");
In my case I need to insert a row with text 'Please dial *001 for help'.
In this case the special character is an asterisk.
By using direct insert using sqlPlus it failed with error "SP2-0734: unknown command beginning ... "
I tryed set escape without success.
To achieve, I created a file insert.sql on filesystem with
insert into testtable (testtext) value ('Please dial *001 for help');
Then from sqlPlus I executed
#insert.sql
And row was inserted.
You can either use the backslash character to escape a single character or symbol
'Java_22 \& Oracle_14'
or braces to escape a string of characters or symbols
'{Java_22 & Oracle_14}'