开发者

How to write ' in SQL query?

开发者 https://www.devze.com 2023-01-24 11:51 出处:网络
i need to use the Characters \' in access query. but if i write select Fname from MEN where Fnale = \'j\'o\' i get error

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

0

精彩评论

暂无评论...
验证码 换一张
取 消