简体   繁体   English

C#字符串替换问题

[英]C# string.Replace problem

I have a string like this: 我有一个像这样的字符串:

string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address, @address2)"

then I replace @address with 'Elm Street' using 然后我将@address替换为'Elm Street',使用

query = query.Replace("@address", "'" + "Elm Street" + "'");

and the result become: 结果变成:

INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, 'Elm Street', 'Elm Street'2)

how to get the result: 如何获得结果:

INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, 'Elm Street', @address2) ?

If this is a SQL query you going about it wrong - you should use SqlParameter to parametrize your query, no need for string replacement: 如果这是一个SQL查询,那么您会出错-您应该使用SqlParameter来对您的查询进行参数设置,而不需要替换字符串:

string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address, @address2)";

using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
    cmd.Parameters.Add(new SqlParameter("@address", SqlDbType.NVarChar)).Value = "Elm Street";
    //add other parameters

    cmd.ExecuteNonQuery();
}

Well, first I should mention that normally you shouldn't be doing this at all. 好吧,首先我要提一提,通常您根本不应该这样做。 You should put the values in parameter objects that you use in the command. 您应该将值放在命令中使用的参数对象中。

If you really need to do that for some weird reason, you can use a regular expression to match all parameters, and replace one of them: 如果出于某些奇怪的原因确实需要这样做,则可以使用正则表达式来匹配所有参数,并替换其中一个参数:

query = Regex.Replace(query, @"@\w+", m => {
  if (m.Value == "@address") {
    return "'Elm Street'";
  } else {
    return m.Value;
  }
});

How about: 怎么样:

string query = "INSERT INTO CUSTOMER (id, name, address, address2) VALUES(@id, @name, @address1, @address2)";
query = query.Replace("@address1", "'Elm Street'");

Sometimes the simplest solution is the right one. 有时,最简单的解决方案是正确的解决方案。 Not in this case. 在这种情况下不行。 You should really use the SqlCommand approach. 您应该真正使用SqlCommand方法。

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

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