【问题标题】:How can I create A template from sql query by using C# and regex?如何使用 C# 和正则表达式从 sql 查询创建模板?
【发布时间】:2019-10-22 20:43:14
【问题描述】:

我正在尝试使用 C# 和正则表达式从 sql 查询创建模板,但我无法成功。我该怎么做?

例如:

我的 sql 选择查询:

select c.[Id], C.Name from Customer c.Surname='Smith' and c.Address like 'Newyork'

一定是:

select c.[Id], C.Name from Customer c.Surname='{Surname}' and c.Address like '{Address}'

另一个示例:

select c.[Id], C.Name from Customer c.Surname='Smith' and c.Address = 'xyx glk'

一定是:

select c.[Id], C.Name from Customer c.Surname='{Surname}' and c.Address = '{Address}'

另一个:

UPDATE table_name
SET column1 = 'value1', column2 = 'value2'
WHERE condition;

一定是:

UPDATE table_name
SET column1 = '{column1}', column2 = '{column2}'
WHERE condition;

我需要你的帮助才能做到。如何在 C# 中使用正则表达式?

【问题讨论】:

  • 为什么是正则表达式?您是否从一些已保存的 SQL 查询开始并尝试在 C# 中生成调用代码?
  • 需要更好地定义你想要做什么,使用 C# 的正则表达式很简单,你可以找到很多在线教程,但我觉得这不是解决方案。你能再解释一下吗
  • 这是错误的。您必须通过 PARAMETERS 传递这些数据
  • 为什么不使用 SQL 参数?为什么要使用正则表达式?
  • 当心:xkcd drop bobby tables 或xkcd.com/1409

标签: c# sql .net regex


【解决方案1】:

也许你会从中得到一些想法。 它正在工作。

 string strtext = @"select c.[Id], C.Name from Customer c.Surname='Smith' and c.Address = 'xyx glk'";
Regex rex= new Regex(@"([^\s.]+)\s*=\s*'(.*?)'");
var replaced = rex.Replace(strtext, "$1={$1}");

演示:https://regex101.com/r/aUhESX/3

【讨论】:

  • 你真棒!你救了我的命!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 2017-06-18
  • 2023-04-06
  • 2021-08-22
  • 1970-01-01
相关资源
最近更新 更多