SQLite Add Not Escaping Apostrophe - c#

I am attempting to insert data using the SQLiteParameter.Add function, like this:
sqlite_cmd.CommandText = "INSERT INTO charity (trans_date, description, amount) VALUES (#trans_date, #description, #amount);";
sqlite_cmd.Parameters.Add(new SQLiteParameter("#trans_date", transDate));
sqlite_cmd.Parameters.Add(new SQLiteParameter("#description", description));
sqlite_cmd.Parameters.Add(new SQLiteParameter("#amount", amount));
sqlite_cmd.ExecuteNonQuery();
Description is a string. When I use an apostrophe in description, it's not being escaped correctly. It's being inserted with two backslashes, as shown in the picture.
Can't seem to find a way to get this to work. Any suggestions?

Related

How to insert '' (2 apostrophes) into sql

I need to insert '' (2 apostrophes) into a column.
Just the apostrophes without any text.
But I end up inserting \'\' (apostrophes with backslashes)
NpgsqlCommand Cmd = new NpgsqlCommand("INSERT into Table(Col) VALUES(#value), conn);
Cmd.Parameters.AddWithValue("#value", "''");
Cmd.ExecuteNonQuery();
Result: \'\' Appears in my table.
If I use less or more apostrophes it inserts fine but I need exactly 2 and then for some reason backslashes appear.
There seems to be a lot of confusion in the results above.
Npgsql does not perform any escaping in parameters, because they are sent out of band and are not treated in SQL. If your parameter value contains a C# string with two apostrophes, that is what will get inserted into the database.
After running your code above and using psql, I get the following:
var cmd = new NpgsqlCommand("INSERT into foo (name) VALUES (#value)", conn);
cmd.Parameters.AddWithValue("#value", "''");
cmd.ExecuteNonQuery();
npgsql_tests=# select * from foo;
name
------
''
(1 row)
Maybe pgadmin shows values with backslashes - I don't know - but that would be a display issue.
Finally, if you really want to insert a constant value (as opposed to a user-provided one), there's no reason to use parameters. Just embed your value in SQL:
INSERT INTO foo (name) VALUES ('''''');
There are six apostrophes in there: 2 as the string delimiters, and two more escaped apostrophes (in SQL, '' is the escaped form of a single literal apostrophe).
However, if you're reading input from the user, definitely use a parameter.
Try to double up each apostrophe.
Cmd.Parameters.AddWithValue("value", "''''");
Adding an empty text box and using it's text value somehow let's me insert the double apostrophes.
So the answer would be
NpgsqlCommand cmd = new NpgsqlCommand (INSERT into Table (Col) VALUES (#value);
Cmd.Parameters.AddWithValue("#value", textBox1.text);
Cmd.ExecuteNonQuery();
Where texBox1 is just an empty text box.
Probably not the best way of doing this but it works for now.

SQLInjection with Npgsql/Postgres

I want to learn how SQLInjection is working with the PostgresqlDb. I am using the Npgsql in C#.
So this is my Query, which is called, when I rename a folder:
cmd.CommandText = "UPDATE allfolder.folder SET folder_name = '" + foldernamenew + "'";
cmd.ExecuteNonQuery();
I now tried to pass the following value into the textfield:
abcdef; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,"aaaaaaa");
Then AJAX is fired.
The output I assumed is, that all folders in the table has the folder_name "abcdef" and that I have a new folder with the id "56" called "aaaaaa". This is not the case, because the semicolon is not recognized as delimiter and so the name of each folder_name are "abcdef; INSERT INTO ....". I do not want to change it on DB side that multiqueries are allowed.
So my questions are:
How do I need to prepare the SQL statement, that I achieve a Injection?
Is an injection even possible, when you are not allowed to execute a second qry because the semicolon isn't recognized?
I am only talking about Npgsql and postgres.
As Laurenz mentioned above, this should work:
abcdef'; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,'aaaaaaa'); -- test
Make sure, that you don't mix single and double quotes. A common mistake in SQL. You need the single quote before the semicolon, otherwise it is in the textstring, because you have no delimiter.
“Multiqueries” (several queries in one line, separated by semicolon) are always allowed in PostgreSQL.
Your problem are the multiple errors in your SQL:
Missing single quote after abcdef.
Double quotes instead of single quotes around aaaaaaa.
No single quote or line comment at the end of the statement.
Speaking pointedly: you have to learn SQL before you can learn SQL injection.

Access string which includes single quote from SQL Server 2008

I am creating a website in C# (Visual Studio 2010). I have got string values in my database which contain single quotes. I replaced them with double single quotes. But while populating the data into a CheckBoxList, the double single quotes are displayed instead of a single quote.
My query is:
SqlDataSource1.SelectCommand = select column1 from table1 WHERE column1<>'"+var1+"'";
You can escape the quotes using two single quotes like so:
"select column1 from table1 where column1 <> ''"+var1+"''";
But remember you're opening yourself up for SQL injection attack. Use SQL Parameters appropriately.
Instead of storing fudged data in your database and then changing it back on output, you should be escaping the single quotes in your query - for MSSQL, single quotes are escaped by doubling them.
However, you'll get a more secure and faster-running query if you parameterise it and assign the value (which now doesn't need escaping) to a SqlParameter object when you make your connection.
If your var1 is a variable, your code does not surround it double single quotes.
I think the right syntax should be something like;
"select column1 from table1 WHERE column1 <> '" + String.Format("''{0}''", var1) + "'";
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
I stopped storing the single quotes in the database to double single quotes (' '). Instead, as suggested, I used a parameterized query. I stopped using an SqlDataSource.
Code:
SqlCommand cmd=new SqlCommand("select column1 from table1 where column1<>#var1",conn);
cm.Parameters.Add("var1",SqlDbType.VarChar).Value=var1;
rdr=cmd.ExecuteReader();

I want to store apostrophe in message box such as john's watch.It show erreor near 's

Please help me to store apostrophe. I m creating a website (C#, .net, SQL Server) and want to have a message box for the users but the problem is that when I inserts any message such as John's it shows an error near ''s'.
Please tell me how could I store apostrophe in database
I used nvarchar, varchar and everything but failed to store apostrophe containing messages.
A general solution is to write message with double apostrophe but this is not a solution for a website
You are open for SQL-Injection. Don't concatenate strings to build your query. Instead use SQL-Parameters. That also makes your code more readable and prevents errors like yours.
Here's an example:
int amt;
using (var con = new SqlConnection(ConnectionString)) {
var sql = "INSERT INTO dbo.Message(UserID, Message) VALUES(#UserID, #Message);";
using (var cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("#UserID", userID); // passed as argument
cmd.Parameters.AddWithValue("#Message", txtMessage.Text); // f.e. "John's"
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
}
The same works also with other sql like UPDATE commands.
The problem is that you need to escape Apostrophe by another Apostrophe.
For example have a look at:http://sqlfiddle.com/#!3/d2f75/1
CREATE TABLE tblTEst( col1 NVARCHAR(50))
INSERT INTO tblTest
(Col1)
SELECT 'John''s'
The best solution is to use a prepared statement (or whatever the equivalent in C# is) where your SQL only contains placeholders and you pass the actual values through a different method.
In a character literal, the single quote ' can be used by simply doubling it:
insert into foo (bar)
values
('John''s');
use CHAR(39)between john & s like this: 'john'+CHAR(39)+'s'

A simple SQL problem: Making an SQL insert statement with text string that contain ' characters

I follow the syntax of
INSERT INTO Table1
VALUES (value1, value2, value3…)
This has worked fine so far. But now I have some values that contain normal English text like "I'm going home". The ' character ruins the SQL command in C#. I have written the following:
command.CommandText = "INSERT INTO Bio VALUES ('" + name + "','"I'm going home" + "');
evaluates to
INSERT INTO Bio VALUES ('Peter','I'm going home')
which obviously will not work. How do I make sure special character will not ruin the SQL statements?
Use SqlParameter for heaven's sake. Otherwise your program will be vulnerable to SQL Injection. It will also solve your problem with the special characters.
Learn about parameterized queries for your provider. They exists for Odbc, OleDb, Sql, etc.
command.CommandText = "INSERT INTO Bio Values (#name, #text)";
command.Parameters.Add(/* appropriate param type for your provider */); // add for #name, #text, etc.
// execute query
Use two single quotes whenever there is a single quote you want to escape
Also instead of building your queries like this, you should use parameterized queries in a language of your choice. Escaping the characters yourself opens the door for SQL Injections.
Usually you can escape a single quote by screening with another one.
For example the following is a valid statement
INSERT INTO myTable (Column1) VALUES ('Hello I''m Jack');
However I suggest you using parameters.
command.CommandText = "INSERT INTO Bio VALUES (#Name, #OtherValue)";
command.Parameters.AddWithValue("Name", name);
command.Parameters.AddWithValue("OtherValue", "I'm going home");
One addition point in favor of using parameters is that you are free from burden of formatting and other stuff. I mean date values, uniqueidentifiers, etc.
I do use
HttpUtility.HtmlEncode(text)
It makes all that SQL injection stuff disappear, and it seems easier than to use parameters.
Don't forget to use
HttpUtility.HtmlDecode(text)
to get your input back in the form you received it

Categories

Resources