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

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

Related

SQL syntax error when I try to update long string with non-alphanumeric charcters

I'm trying to update a string of characters in a table, but the string contains a lot of non-alphanumeric characters. It's causing SSMS to return errors when I try to run the update statement.
I'm running a fairly standard update statement:
UPDATE Table
SET TextObj = 'asfsdsad $$%))# asdfas'd #$%^&)asfda'
WHERE ID = 6 AND Name = 'Text'
You can see the string I'm trying to update contains a lot of non-alphanumeric characters. I've enclosed the string in single quotes like I would normally do, but SSMS is throwing a syntax error:
Unclosed quotation mark after the character string ' Where ID = 6 and Name = 'Text''.
I've also tried double quotes to no avail. How do I get this string updated?
You have to escape the single quote inside of the string:
UPDATE Table
SET TextObj = 'asfsdsad $$%))# asdfas''d #$%^&)asfda'
WHERE ID = 6 AND Name = 'Text'

How to replace escape character (\') from json data using sql query?

json_data = {"jobId":"7f","created":"2020-05-24T00:22:55.705373Z","updated":"2020-05-24T00:31:03.716279Z","status":"DONE","sha265sum":"d3adf4466b5c88027478e4c","result":"FAILED","errors":[{"errorCode":"S_ERROR","errorDetail":"In: Can\'t create in vms : Error when sending ing s request:INTERNAL: PreparedStatementCallback; Duplicate entry \'Mob 66 The L\' for key \'uc\'; nested exception is Violation Exception: Duplicate entry \'Mob 66 The L\' for key \'uc\'","sId":47}
I want to replace (\') with empty char in the above data, using oracle sql query; i am trying to use
select replace(d.json_data,'\"', '"') from json_logs d where d.json_data like '%Error%'; but no luck
Thank you!
Your string has escaped single quotes, \'. But you are doung
replace(d.json_data,'\"', '"')
which is looking for escaped double quotes, \".
So you need to use:
replace(d.json_data,'\''', '''')
which also doubles-up the single quotes within the search and replacement strings, to perform Oracle's own escape of those.
You could also use the alternative quoting mechanism:
replace(d.json_data,q'[\']', q'[']')
but I'm not sure that's a lot clearer in this case.
db<>fiddle

How do I use single quotes as part of a string in SQL

I have a where clause that uses a string,
Where
pm.Alias = 'Toys'R'Us France'
However part of the string uses single quotation marks, 'R'
How do i wrap up the whole string to pass through into my Where clause
I cannot use:
Where
pm.Alias = 'Toys''R''Us France'
As i need the whole string encased, as i will use this in Excel to pass this as a paramter into my query
in SQL, if you want to have Single Quotes inside a string, then you should specify it as 2 consecutive single quotes for every single quote in your string. So
Where
pm.Alias = 'Toys'R'Us France'
should be written as
Where
pm.Alias = 'Toys''R''Us France'
You might try using extra quotes after and before the existing quotes.
In this case add quote before and after 'R', and the query will be like below.
Where
pm.Alias = 'Toys''R''Us France'
I recently face this issue in my sqlite database, you can resolve using like this.
Where
pm.Alias = "Toys'R'Us France"
use double quote (") instead of single quote (') after equal sign.

Parsing a string with double quotation in it

I have a table in which one of the fields contains the string 302720"?.
When I try to do a substring of that string, it returns an error. I understand that it is because of the double quotes within the string.
I tried replacing the quotation with REGEXP_REPLACE, even that didn't work.
Below is the SQL statement:
SELECT SUBSTR("302720"?", 0, 3)
Any comments regarding this would be appreciated.
Please see below for an example. You didn't list the DBMS, so I assumed SQL Server.
Code
CREATE TABLE SUBSTR_TEST(STRING VARCHAR(50) NOT NULL)
INSERT INTO SUBSTR_TEST
VALUES('302720"?')
SELECT * FROM SUBSTR_TEST
SELECT SUBSTRING(REPLACE(STRING,'"',''),0,3) AS STRING FROM SUBSTR_TEST
Result
If you're doing this by hand, either use different quotes...
SELECT SUBSTR('302720"?', 0, 3)
Or you can escape the quote. You can do this by doubling the quote:
SELECT SUBSTR("302720""?", 0, 3)
Or you can use the traditional \ escape character.
SELECT SUBSTR("302720\"?", 0, 3)
If you're doing this in a program, use a prepared statement with bind parameters. This avoids having to deal with escapes as well of avoiding a host of security problems. The specifics differ by language, but it's usually something like this:
handle = connection.prepare("SELECT SUBSTR(?, ?, ?)");
handle.execute('302720"?', 0, 3)
result = handle.fetch
It's analogous to passing variables into a function.

insert string with " ' " to oracle

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'')';