SQL查询中的转义字符[重复]

时间:2022-10-16 22:25:36

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to update a database using this query:

我正在尝试使用此查询更新数据库:

string query = "UPDATE pagine SET titolo= '" + pa.titolo + @"', contenuto = '" + pa.contenuto + @"' WHERE id= " + pa.id;

I can't get it working. More details are available at Updating an mdb database table

我无法让它发挥作用。更新mdb数据库表可以获得更多详细信息

The problem might be the fact that i have some apostrophes in the title and the content. I tried using Regex.Escape but it just adds tons of \\\ to the content.

问题可能是我在标题和内容中有一些撇号。我尝试使用Regex.Escape但它只是在内容中添加了大量的\\\。

Is there any way to escape just the ' and " characters in ASP.NET?

有没有办法逃脱ASP.NET中的'和'字符?

Note: since i'm italian i use italian names for variables but i translated them for better clarity in the other question posted yesterday.

注意:因为我是意大利语我使用意大利语名称作为变量但我翻译它们以便在昨天发布的另一个问题中更清晰。

3 个解决方案

#1


4  

My advice is to use SqlCommand object with SqlParameters to avoid all the concatenation and escape chars fuss. They'll automatically handle all of it for you. In addition they'll save you from SQL injection attacks too.

我的建议是使用带有SqlParameters的SqlCommand对象来避免所有连接和转义字符大惊小怪。他们会自动为您处理所有这些。此外,它们还可以帮助您免受SQL注入攻击。

If you have option, I'd suggest that you go for typed DataSet approach and create a Typed Query for yourself. Then you can call that as a regular .NET function in your code.

如果您有选项,我建议您使用类型化DataSet方法并为自己创建一个Typed Query。然后,您可以将其称为代码中的常规.NET函数。

#2


0  

In C# you can escape " like below -> " to \"

在C#中你可以“像下面 - >”逃到“

"ABELE\"o\""

you can escap single Quotes ' like below ' to ''

你可以把单个行情'下面'改为'''

"ABELE''o"

#3


0  

SQLParameter are safer as you can't forget to clean up text.
You can just escape the text.

SQLParameter更安全,因为您不能忘记清理文本。你可以逃避文本。

string userText = @"you realy shouldn't do this";

string sqlSafeText = sqlSafeText.Replace(@"'", @"''");

#1


4  

My advice is to use SqlCommand object with SqlParameters to avoid all the concatenation and escape chars fuss. They'll automatically handle all of it for you. In addition they'll save you from SQL injection attacks too.

我的建议是使用带有SqlParameters的SqlCommand对象来避免所有连接和转义字符大惊小怪。他们会自动为您处理所有这些。此外,它们还可以帮助您免受SQL注入攻击。

If you have option, I'd suggest that you go for typed DataSet approach and create a Typed Query for yourself. Then you can call that as a regular .NET function in your code.

如果您有选项,我建议您使用类型化DataSet方法并为自己创建一个Typed Query。然后,您可以将其称为代码中的常规.NET函数。

#2


0  

In C# you can escape " like below -> " to \"

在C#中你可以“像下面 - >”逃到“

"ABELE\"o\""

you can escap single Quotes ' like below ' to ''

你可以把单个行情'下面'改为'''

"ABELE''o"

#3


0  

SQLParameter are safer as you can't forget to clean up text.
You can just escape the text.

SQLParameter更安全,因为您不能忘记清理文本。你可以逃避文本。

string userText = @"you realy shouldn't do this";

string sqlSafeText = sqlSafeText.Replace(@"'", @"''");