How to write ' in SQL query? - c#

i need to use the Characters ' in access query.
but if i write select Fname from MEN where Fnale = 'j'o' i get error
how to write the Characters '
thank's in advance

Try a backslash \' or two quotes ''.
This depends on your database. MySQL uses \' and Microsoft SQL and MS Access uses two quotes ''.

Single quotes can be escaped with two single quotes.
SELECT Fname FROM MEN WHERE Fnale = 'j''o'

For SQL Server:
var cmd = new SqlCommand("select fname from MEN where fnale = #query", myConnection);
cmd.Parameters.AddWithValue("#query", "j'o");
All solutions where you add your parameter to the sql string yourself are wrong (or at least high risk), because they are vulnarable for a SQL Injection Attack.
You mention "access query", for Microsoft Access / Ole use the following syntax:
var cmd = new OleDbCommand("select fname from MEN where fnale = ?", myConnection);
cmd.Parameters.AddWithValue("?", "j'o"); // Order does matter

I would use a literal string to avoid escaping everything
string query = #"select Fname from MEN where Fnale = 'jo'";
If you are escaping this with respect to SQL, then use another single quote to escape the quotes:
select Fname from MEN where Fnale = ''jo''

As others said, you can escape the quotes. But if you are sending that query from C#, then it's better to use parameters - that way all escaping is done for you, so you can't forget some special case where user input can still cause unwanted effects. (little bobby tables, anyone? :-) )

Try replacing ' with ''

Related

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

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.

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'

How to insert string containing single or double quotes

If I want to insert a statement which contains quotation mark, how is it possible ?
For Example I have a text box and I enter:
Future Swami Vivekananda’s grand father's name was "____" .
If you use properly parameterized statements, you shouldn't need to worry about it. Something like this (though please don't learn C# techniques from me):
string sql = #"UPDATE dbo.table SET col = #p1 WHERE ...;";
string myString = #"hello'foo""bar";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#p1", SqlDbType.VarChar, 30).Value = myString;
(Though you really should be using stored procedures.)
If you are building your strings manually (which you really, really, really shouldn't be doing), you need to escape string delimiters by doubling them up:
INSERT dbo.tbl(col) VALUES('hello''foo"bar');
Use a parameterized query - then quotes don't matter at all. Also - your database doesn't get taken over by SQL injection - so win/win really.
You can double up the quote:
INSERT INTO table
VALUES ('Future Swami Vivekananda''s grand father''s name was "____"')

How to escape simple SQL queries in C# for SqlServer

I use an API that expects a SQL string. I take a user input, escape it and pass it along to the API. The user input is quite simple. It asks for column values. Like so:
string name = userInput.Value;
Then I construct a SQL query:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'",
name.replace("'", "''"));
Is this safe enough? If it isn't, is there a simple library function that make column values safe:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'",
SqlSafeColumnValue(name));
The API uses SQLServer as the database.
Since using SqlParameter is not an option, just replace ' with '' (that's two single quotes, not one double quote) in the string literals. That's it.
To would-be downvoters: re-read the first line of the question. "Use parameters" was my gut reaction also.
EDIT: yes, I know about SQL injection attacks. If you think this quoting is vulnerable to those, please provide a working counterexample. I think it's not.
I was using dynamic sql (I can hear the firing squad loading their rifles) for search functionality, but it would break whenever a user searched for somebody with a surname like "O'Reilly".
I managed to figure out a work-around (read "hack"):
Created a scalar-valued function in sql that replaced a single quote with two single quotes, effectively escaping the offending single quote, so
"...Surname LIKE '%O'Reilly%' AND..."
becomes
"...Surname LIKE '%O''Reilly%' AND..."
This function gets invoked from within sql whenever I suspect fields could contain a single quote character ie: firstname, lastname.
CREATE FUNCTION [dbo].[fnEscapeSingleQuote]
(#StringToCheck NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #Result NVARCHAR(MAX)
SELECT #Result = REPLACE(#StringToCheck, CHAR(39), CHAR(39) + CHAR(39))
RETURN #Result
END
Not very elegant or efficient, but it works when you're in a pinch.
One may wish to replace ' with '' instead of parameterizing when needing to address the ' problem in a large amount of ad hoc sql in a short time with minimal risk of breakage and minimal testing.
SqlCommand and Entity Framework use exec sp_executesql....
So there really is an alternative to raw strings with your own escaping pattern presumably. With SqlCommand you are technically using parameterised queries but you're bypassing the ADO.Net abstraction of the underlying SQL code.
So while your code doesn't prevent SQL Injection, the ultimate answer is sp_executesql not SqlCommand.
Having said that, I'm sure there are special handling requirements for generating an SQL Injection-proof string which utilizes sp_executesql.
see: How to return values from a dynamic SQL Stored Procedure to the Entity Framework?
Simple:
const string sql = "SELECT * FROM SOME_TABLE WHERE Name = #name";
and add the #name parameter with value:
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#name", name);
If you need to escape a string for a MSSQL query try this:
System.Security.SecurityElement.Escape(Value)

Categories

Resources