简体   繁体   中英

C#, replacing special character in query

I have a record in a database containing special characters like &,' (apostrophe).

The record look like this.. stack'overflow .

In my query I have written like this.

where name = ' " +name+ " ' ";

Suppose the name is stack'overflow - then it gives me a syntax error.

How to solve it?

I am using C#

Your question is very unclear but the answer is almost certainly going to be not to include data in SQL statements. Use a parameterized query instead, so you don't need to worry about performing any escaping etc yourself.

As an example, have a look at the SqlCommand.Parameters documentation - but be aware that different DB providers use different approaches to parameters (eg named vs positional).

Dont append text into a query. Search google for SQL Injection. Its a big problem and you shouldnt be doing this. You are potentially leaving yor application open to serious attack.

One solution is to use SQL parameters instead in your queries. Take a look here for further information : Adding Parameters to Commands

Use parameterized queries . They will handle the escaping of special characters for you and will help guard against SQL injection attacks. They also provide a better mechanism for the SQL server to cache an execution path to improve performance.

Never, ever, ever use concatenated SQL.

A better way to do this would be to use parameterized queries. String building for SQL can be pretty dangerous if the data is not santized properly beforehand.

Try something like this:

string query = "SELECT * FROM myTable WHERE name = @p_name";

SqlCommand cmd = new SqlCommand(query, sqlConnection);
cmd.Parameters.AddWithValue("@p_name",yourTextItem);

Updated for your situation:

string myName = TextBox1.Text;

string query = "SELECT * FROM myTable WHERE name LIKE %@p_name%";

SqlCommand cmd = new SqlCommand(query, sqlConnection);
cmd.Parameters.AddWithValue("@p_name",myName);

You need to use parameters.

For more information, consult the documentation for whatever you're using.

replace "'" with "''" in your name variable before passing in and you should be fine.

EDIT:

Yes This would just be a temporary solution. To permanantly get rid of your problem please use parameterized query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM