开发者

C# string.Replace problem

I have a string like this:

string query = "INSERT INTO CUSTOMER (id, name, address, address2) VAL开发者_开发知识库UES(@id, @name, @address, @address2)"

then I replace @address with 'Elm Street' using

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜