简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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