How to express the Parameters correctly in SQLite Select statement - sqlite

I am just not sure the correct way to express the parameters in the SQLite Select statement with parameters.
In the Select-statement , how to express?
1) use =? or ='?'
"Is_Offline_Trans =?" or "Is_Offline-Trans='?'"
2) for Number,
Example "0" or "'0'"
3) For String
Example: "SQlite's Rocking solid" or "'SQLite's Rocking Solid"
is this correct?
here my Parameterized Select statement:
string string Company ="Anderson's Studio";
var Orders = db.Query<SalesOrderHeader >("Select * From SalesOrderHeader Where Is_SyncToNAV =?" +
" AND Is_Offline_Trans =?" +
" AND DataEntryComplete =?" +
" AND Company =?","0" ,"1" ,"1", Company);
Can I do hard code for the company this way:
" AND Company =?", "Anderson's Studio"
Your help is greatly appreciated.
Thanks

Inside the SQL statement, a parameter is just a single ?.
With quotes, '?' would be a string containing a single question mark character.
The parameter values are not given in SQL. but come from your program.
Therefore, you must write them correctly for the programming language that you're using.
(C# does not quote numbers.)

Related

How do safely I add a raw string to a query?

My SQLite query :
let data = db.getAllRows(sql"""
SELECT name, source, uploaded_at, canonical_url, size
FROM table
WHERE name like ?
ORDER BY ? DESC
LIMIT ?
OFFSET ?
""", &"%{query}%", order, limit, offset)
Nim adds single quotes to any string replacing ?. I can manually build the SQL string and then use sql(string), but the input then isn't escaped. Is there some other token apart from ? that does not add '?
To answer your title question: "How to safely add a raw string to a query", you can use dbQuote:
import db_sqlite
let
a = "unes'caped %' string"
b = "my prefix ->"
c = "<- my suffix"
d = b & dbQuote(a) & c
echo d
This will print my prefix ->'unes''caped %'' string'<- my suffix, adding quotes before/after and escaping any ones inside. This string is presumably safe to pass as an sql statement. You should get the same result as if you had used ? with extra parameters.

can anyone tell me what's wrong in this?

public void deleteData(String name,int itemID){
SQLiteDatabase db=getWritableDatabase();
String query="DELETE FROM "+ TABLE_NAME + " WHERE "+ "'"+ COL1 +"'"+ " = "+ itemID + " AND "+ "'" + COL2 + "'" +" ="+ " '"+ name + "'";
db.execSQL(query);
db.execSQL(query);
}
The following are wrong or could be considered as wrong.
There should be no need to call the exact same query twice.
It is considered better to use the Android SDK's convenience methods when they suit (instead of using the execSQL method the delete method is more appropriate).
There is the potential for SQLinjection attacks when parameters are used directly in strings that are executed directly as SQL (note resolving 2 and using the appropriate parameters resolves this issue).
There is, unless the columns are named with invalid names, no need to enclose column names in single quotes or alternative characters (invalid names can make life difficult so if used they would be considered wrong by many).
If the delete (the first one), is not working or if the delete appears to not return an appropriate result after using pragma count_changes that could be due to the row not existing (did the row get inserted?) or that the 2nd query which would delete nothing is hiding the result of the first query.
pragma count_changes is deprecated in later version of SQLite so should no longer be used (albeit that Android's SQlite version is typically some way behind).
As a fix to all bar the id not existing you could use the following :-
public int deleteData(String name,int itemID){
SQLiteDatabase db=getWritableDatabase();
String whereclause = COL1 + "=? AND " + COL2 + "=?";
String[] whereargs = new String[]{String.valueOf(int),name};
return db.delete(TABLE_NAME,whereclause,whereargs);
}
Note that the methods signature results in an int being returned, this will be the number of rows deleted.

Do braces { } protect me from sql injection with a dynamic query in Oracle 11g?

Read this:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
On the dynamic sql part it has various such as this:
So, if you had an existing Dynamic query being generated in your code that was going to Oracle that looked like this:
String query = "SELECT user_id FROM user_data WHERE user_name = '" + req.getParameter("userID")
+ "' and user_password = '" + req.getParameter("pwd") +"'";
try {
Statement statement = connection.createStatement( … );
ResultSet results = statement.executeQuery( query );
}
You would rewrite the first line to look like this:
Codec ORACLE_CODEC = new OracleCodec();
String query = "SELECT user_id FROM user_data WHERE user_name = '" +
ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getParameter("userID")) + "' and user_password = '"
+ ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getParameter("pwd")) +"'";
And it would now be safe from SQL injection, regardless of the input supplied.
But the later is says:
Oracle 10g escaping
An alternative for Oracle 10g and later is to place { and } around the string to escape the entire string. However, you have to be careful that there isn't a } character already in the string. You must search for these and if there is one, then you must replace it with }}. Otherwise that character will end the escaping early, and may introduce a vulnerability.
I did not see an example, but does this mean I can use braces instead of the Codec ORACLE_CODEC....etc.? Does anyone have an example? Thanks.
No, this is not an injection prevention technique. The only way to be 100% sure that you're not vulnerable to injection is to use prepared statements and bind parameters for all user input that needs to be inserted into the query. Anything less than that, and you're pretty much just rolling the dice.

creating a sufficient query search sql

I am writing a query to allow a user to search on what they provide keywords in asp.net, C# and mssql:
string projectPart = null;
string categoryPart = null;
string descriptionPart = null;
if (this.Textbox_ProjectNr.Text.Trim().Length > 0)
projectPart = " AND Number='" + this.Textbox_ProjectNr.Text.Trim() + "' ";
if (this.Textbox_Category.Text.Trim().Length > 0)
categoryPart = " AND Category LIKE '%" + this.Textbox_Category.Text.Trim() + "%' ";
if (this.Textbox_pDescription.Text.Trim().Length > 0)
descriptionPart = " AND ProductDescription LIKE '%" + this.Textbox_pDescription.Text.Trim() + "%' ";
string query = "SELECT * from Project = p.ID " + projectPart + descriptionPart + categoryPart;
I dont know whether this query is sufficient for a traditional query search. Because I see there are some bottlenecks of this search:
if the user does not type anything, it returns all of the data => For this I only do the query when one of the fields are filled.
if the user provides some keywords "P" for each field, the result will be millions of data.
I dont know how to improve the search query basically. any suggestions are appreciated.
Thanks in adavance.
The most important improvement is to protect you code against SQL injection attacks.
You should not concatenate the raw input in the SQL string. If someone searches for the following text for example:
Bwah ha ha'; DROP DATABASE northwind; PRINT'
This will be added to your query to produce
SELECT *
FROM mytable
WHERE category LIKE '%Bwah ha ha'; DROP DATABASE northwind; PRINT'%'
This is a valid SQL command and will happily execute and drop your database (or do anything else the attacker wants)
For more information see SQL Injection and Santitizng Inputs.
You must make this query injection proof! Do not concatenate user entered values, but use parameters, like this:
SqlCommand cmd = new SqlCommand(#"
SELECT * from Project
WHERE
( Number = #Number OR #Number IS NULL ) AND
( Category LIKE #Category OR #Category IS NULL ) AND
( ProductDescription LIKE #ProductDescription OR #ProductDescription IS NULL )", conn);
if(!String.IsNullOrEmpty(this.Textbox_ProjectNr.Text.Trim()))
cmd.Parameters.AddWithValue("#Number", this.Textbox_ProjectNr.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_Category.Text.Trim()))
cmd.Parameters.AddWithValue("#Category", this.Textbox_Category.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_pDescription.Text.Trim()))
cmd.Parameters.AddWithValue("#ProductDescription", this.Textbox_pDescription.Text.Trim());
Also, you can add some client validation on user entered values. For instance, ask for more than three (?) characaters before running that query.
<asp:TextBox ID="Textbox_ProjectNr" runat="server" />
<asp:RegularExpressionValidator ID="Textbox_ProjectNr_Validator" runat="server"
ControlToValidate="Textbox_ProjectNr"
ErrorMessage="Minimum length is 3"
ValidationExpression=".{3,}" />
First of all, you must protect yourself from sql injections. You haven't specified what connection to the database you are using but most libraries allow adding the parameters in a different field, so they are sanitized automatically.
Secondly, you can (and should) limit the results count using the "LIMIT" (for mysql) or "TOP X" Like so:
Select * from TableName LIMIT 100 or Select TOP 100 * from TableName

Escape single quote character for use in an SQLite query

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

Resources