如何将'字符转换为' C#中的角色? [英] How can I convert ' character to " character in C#?
问题描述
对于要在C#中发送的sql字符串,我需要将字符串内部的 ' 字符转换为 character。
我尝试了什么:
我试图替换C#中的字符,但我不能。
For a sql string to be sent in C# I need to convert ' character inside the inside the string to " character.
What I have tried:
I tried to replace the characters in C# but I couldn't.
推荐答案
str = str.Replace(',\ );
对于要发送的sql字符串在C#中,我需要将字符串内部的字符转换为字符。
For a sql string to be sent in C# I need to convert ' character inside the inside the string to " character.
不,你没有。
根据描述,你试图在SQL查询中转义特殊字符,因为你正在使用字符串连接来为查询添加参数。但这会使你的代码容易受到 SQL注入 [ ^ ]。
相反,你需要使用参数化查询。这样,你不需要担心特殊字符,你可以只提交不变的值。
例如:
No, you don't.
Based on the description, you're trying to "escape" special characters in a SQL query, because you're using string concatenation to add parameters to the query. But that leaves your code vulnerable to SQL Injection[^].
Instead, you need to use a parameterized query. That way, you don't need to worry about "special" characters, and you can just submit the values unchanged.
For example:
string theName = "Seamus O'Leary";
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("SELECT SomeColumns FROM YourTable WHERE SomeName = @Name And SomeDate >= @MinDate", connection))
{
command.Parameters.AddWithValue("@Name", theName);
command.Parameters.AddWithValue("@MinDate", DateTime.Today);
...
}
你想知道关于SQL注入的一切(但不敢问)特洛伊亨特 [ ^ ]
如何在没有技术术语的情况下解释SQL注入? |信息安全堆栈交换 [ ^ ]
查询参数化备忘单| OWASP [ ^ ]
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
这篇关于如何将'字符转换为' C#中的角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!