Escape special characters in SQL INSERT INTO via C# - c#

I have searched google and haven't found any solution for my issue yet. Basically I have a comments feed that is setup within an image gallery (similar to facebook or stackoverflow comments). Users can post comments and read comments posted by other users. This is working fine. However, if a user tries to post a comment with an apostrophe, I get a nice little web application error:
Incorrect syntax near 's'. Unclosed quotation mark after the character
string ')'.
The comment that I'm posting to SQL is 81's. I'm wanting a solution that will escape all special characters so that whatever the user types in, no matter what, doesn't error out.
Code Behind
Fetcher.postUserComments(connectionString, imagePath, comments.ToString(), userId);
Fetcher
sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES ('" + userId + "', '" + imagePath + "', '" + comments + "', '" + theDate + "')";
The data type is string and I've also tried doing a .ToString() but no luck. Thanks in advance for any helpful input.

You should always use parameterized querys. They help you avoid situations like the one you are having, as well as SQL Injection attacks
sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES (#userId, #imagePath, #userComments, #dateCommented)";
sqlCom.Parameters.AddWithValue("#userId", userId);
sqlCom.Parameters.AddWithValue("#imagePath", imagePath);
sqlCom.Parameters.AddWithValue("#userComments", comments);
sqlCom.Parameters.AddWithValue("#dateCommented", theDate);

You need to duplicate the ' character in comments
comments = comments.Replace("'", "''");
Alternatively, but more safety, is to use Sql parameter, example :
cmd.CommandText = "SELECT * FROM Client, Project WHERE Client.ClientName = #ClientName AND Project.ProjectName = #ProjectName";
cmd.Parameters.Add(new SqlParameter("#ClientName",client.SelectedValue));
cmd.Parameters.Add(new SqlParameter("#ProjectName",projnametxt.Text));

You should NEVER do this...because it allows for easy SQL injection. I could inject malicious sql queries through a comment, something like...
;drop database master;
use parameters instead to avoid sql injection
command.Parameters.Add(new SqlParameter("#Param", value));

Related

Inserting values directly into db-syntax in C#

INSERTing values without parameters is fully understandable why it shouldn't be allowed, where you e.g. want to prevent sql-injection. However I do not understand why it's still a big no doing the following as well:
cmd.CommandText = "SELECT * FROM [Students]
WHERE StudentID = " + studentID + ";";
int getID = (int)cmd.ExecuteScalar();
What's the harm in it when just SELECTing? I don't really understand the point with parameters below. I'm not questioning it, I just want to know the reason why parameters is necessary and what consequences I could get from the code above instead using the option below.
var pStudentID = new SqlParameter("#studentID", SqlDbType.Int);
pStudentID.Value = studentID;
cmd.Parameters.Add(pStudentID);
There are two reasons it's better to use parameters.
Sql Injection - Your first example would be susceptible to a sql injection attack. What this means is if the studentID was being input from a web form, some one could use a '-- to comment out the select string and issue other commands against the database.
Prepare - If you use parameters you can prepare the sql statement, which is sort of a precompile of the syntax. This can be slightly more performant in high volume situations.
Edit: I came across this video on reddit the other day, which is a great example of how sql injection works.sql injection
Assume this input:
var studentID = "''; drop table users;--"
cmd.CommandText = "SELECT * FROM [Students]
WHERE StudentID = " + studentID + ";";
This would if calling this select delete the table users completely.
Parameters would help by approving only legitimate input to be added to the query.

"Data type mismatch in criteria expression" error in Access SQL query from C#

I am getting below Error, When I put Multiple Conditions with WHERE Clause.
Error:- Data type mismatch in criteria expression.
My Query:-
this.query = "UPDATE [Attendance] SET [TimeOut]='" + DateTime.Now.ToShortTimeString() + "' WHERE [Emp_Id]='" + txtEmpId.Text + "'and[Date]='" + this.Date + "'";
Access SQL tends to be rather flexible when accepting Date/Time values as strings. However, since you really should be using a parameterized query anyway because
they're safer (by avoiding SQL Injection issues),
you don't have to mess with delimiters for date and text values,
you don't have to worry about escaping quotes within text values, and
they handle dates properly so your code doesn't mangle dates on machines set to dd-mm-yyyy format,
consider using the following approach
this.query = "UPDATE [Attendance] SET [TimeOut]=? WHERE [Emp_Id]=? AND [Date]=?";
cmd.CommandText = this.query;
cmd.Parameters.AddWithValue("?", DateTime.Now.ToString("H:mm:ss"));
cmd.Parameters.AddWithValue("?", txtEmpId.Text);
cmd.Parameters.AddWithValue("?", this.Date);
cmd.ExecuteNonQuery();

SQL Injection and LIKE statements

What would be the best way to stop SQL injection with a LIKE statement? So here is a example of the code:
string search = Server.HTMLDecode(userEnteredSearchText);
SqlCommand comm = new SqlCommand("SELECT Result WHERE (Keyword LIKE '%" + #search + "%') "
comm.Parameters.Add(new SqlParameter("search", search));
This is what I have been doing other sql statements and it seems like special characters such as ' and % can't break those statements, but I'm guessing with a LIKE statement you need to do a escape key or something?
The following looks a little cleaner to me.
string search = Server.HTMLDecode(userEnteredSearchText);
SqlCommand comm = new SqlCommand("SELECT Result WHERE (Keyword LIKE #search) "
comm.Parameters.Add(new SqlParameter("search", String.Format("%{0}%", search)));
Sorry the quotes are off. You do it precisely like you do with everything else, except that within the SQL you need to concatenate the %'s. Also, HTMLDecode is probably not doing you any good here at all, right? What if they want to search in the db for things that contain "&"
Search = userEnteredSearchText);
SqlCommand comm = new SqlCommand("SELECT Result WHERE Keyword LIKE '%' + #search + '%'");
comm.Parameters.Add(new SqlParameter("search", search));
So in your example, you were closing the SQL literal to put in #search, which is an invalid keyword or variable - you just need to leave that inside the SQL statement. Other DB's, you need to CONCAT the things together. But the bind variable will properly escape the stuff going to the driver.
Avoid single quote for sure in the parameters when you are sending a sql query to database.
Remove any special character present in the parameter in the c# code itself.
I would suggest avoid as many special character as possible.

Using variables in SQL queries in asp.net (C#)

I have an SQL query of this form
string cmdText = "Select * from " + searchTable
+ "WHERE " + searchTable
+ "Name =' " + searchValue + "'";
Basically what I am trying to do is get a particular actor's info from the database's Actors table. The variable searchTable has the value 'Actor' which is the table name and searchValue has the actor's name (which is represented by the ActorName attribute in the Actor's table, here I am trying to form the name of the attribute by concatenating the words 'Actor' and 'Name' )
So, well, all this concatenation results in (or at least should result in) a query of the form:
Select * from Actor where ActorName ='some actor';
But when I try to run this it gives me the error "Incorrect syntax near '=' " in the browser. Could anyone please help?
You can put (and should!) parameters into your SQL queries for the values in e.g. your WHERE clause - but you cannot parametrize stuff like your table name.
So I'd rewrite that query to be:
SELECT (list of columns)
FROM dbo.Actor
WHERE ActorName = #ActorName
and then pass in just the value for #ActorName.
If you need to do the same thing for directors, you'd have to have a second query
SELECT (list of columns)
FROM dbo.Directors
WHERE DirectorName = #DirectorName
Using parameters like this
enhances security (prohibits SQL injection attacks!)
enhances performance: the query plan for that query can be cached and reused for second, third runs
PS: the original problem in your setup is this: you don't have any space between the first occurence of your table name and the WHERE clause - thus you would get:
SELECT * FROM ActorWHERE ActorName ='.....'
If you really insist on concatenating together your SQL statement (I would NOT recommend it!), then you need to put a space between your table name and your WHERE !
Update: some resources for learning about parametrized queries in ADO.NET:
The C# Station ADO.NET Tutorial / Lesson 06: Adding Parameters to Commands
Using Parameterized Queries with the SqlDataSource
You shouldn't concatenate string to SQL, as this will open you up to SQL Injection attacks.
This is a rather long read about dynamic SQL, but worth reading to understand the risks and options.
You should be using parameterized queries instead, though the only way to use a table name as a parameter is to use dynamic SQL.
I urge you to change your approach regarding table names - this will lead to problems in the future - it is not maintainable and as I mentioned above, could open you to SQL Injection.
The error you are seeing is a result of the concatenation you are doing with the "Where " clause - you are missing a space before it. You are also adding a space after the ' in the parameter ending with "Name".
Your resulting string, using your example would be:
Select * from ActorWHERE ActorName =' some actor';
There is a blank missing and one too much:
searchTable + "Name =' "
should read
searchTable + " Name ='"
Beside that, use SQL parameters to prevent SQL injection.
string cmdText = "Select * from " + searchTable + " WHERE Name = '" + searchValue + "'";

Dynamically taking a table name in aspx form using sql server

I'm trying to dynamically accept a table name depending on the conditions satisfied, also the column name is selected dynamically, and so is the comparison value, but I'm getting an error while running it. I'm writing this code in C# and my backend is SQL server 2005. Please help me.
Here is the code:
if( table=="studenttab")
table = "personal_detail";
thisconnection1.Open();
string p = field[0].ToString().ToLower();
string q = code[0].ToString();
SqlCommand thiscommand3 = thisconnection1.CreateCommand();
thiscommand3.CommandText = " Select * from '" + table + "' where '" + p + "' = '" + q + "' ";
// here it gives error "Incorrect syntax near 'personal_detail'." Dont understand!
SqlDataReader thisreader3 = thiscommand3.ExecuteReader();
To answer your specific question, I would guess the error is due to the fact that you are surrounding your table name and column names with single quotes. your object names should not be surrounded with quotes of any kind.
As a side note, please look into the problems associated with SQL injection attacks. The kind of SQL concatenation you are doing here is widely considered a huge security risk.
Your code is missing several closing braces, a closing quote, and it seems to have misleading indentation.

Categories

Resources