简体   繁体   English

C#中的正则表达式

[英]Regular Expressions in C#

I'm trying to do datacontent.executeCommand("string") in C#. 我正在尝试在C#中执行datacontent.executeCommand(“ string”)。 When I am trying to do Insertion I am having trouble because everytime there is a 'word' in a entry I thinks it's a new column, and i throws an exception. 当我尝试执行插入操作时,遇到了麻烦,因为每次条目中都有一个“单词”时,我都认为这是一个新列,并且会引发异常。

How do you turn the 'word' into ''word'' ? 您如何将'word'转换为''word''

You can escape characters in SQL strings with \\. 您可以使用\\来转义SQL字符串中的字符。 However, I believe the best solution to your problem (and a bunch of others, that you'll run into later if you don't do it this way from the start) is SQL Parameters. 但是,我认为,解决您的问题(以及其他很多问题,如果您从一开始就不这样做的话,以后会遇到)的最佳解决方案是SQL参数。

As suggested by Tomas and Jason, it is best to use SQLParameters to avoid these problems. 正如Tomas和Jason所建议的那样,最好使用SQLParameters来避免这些问题。

However, if it requires to many code changes and you need a quick fix, then I would say: You don't need regex for this. 但是,如果需要大量代码更改并且您需要快速修复,那么我会说:您不需要正则表达式 You only need to do a string.replace 您只需要做一个string.replace

string query;
...
query.Replace("'", "''");

If I haven't understood your Q properly and its only instances of 'word' you need to change, you can do: 如果我不能正确理解您的Q,并且您仅需要更改“ word”的实例,则可以执行以下操作:

query.Replace("'word'", "''word''");

I would like to welcome you to the wonderful world of SQL injection, where users can hijack your database by executing malicious SQL due to you executing arbitrary strings ;-) 我想欢迎您进入SQL注入的美好世界,由于您执行任意字符串,因此用户可以通过执行恶意SQL劫持数据库;-)

You really should use parameters (Like those in System.Data.SqlClient) or use the LINQ data model objects generated for you and set values on those and then submit your changes. 您确实应该使用参数(如System.Data.SqlClient中的参数)或使用为您生成的LINQ数据模型对象,并在这些参数上设置值,然后提交更改。 Let the data access layer escape out your values and protect you from a user that might enter text that includes SQL statements like DELETE * FROM IMPORT_TABLE. 让数据访问层逸出您的值并保护您免受可能输入包含SQL语句(例如DELETE * FROM IMPORT_TABLE)之类的文本的用户的侵害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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