0

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) ?

3 Answers 3

5

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1: Don't use String.Replace(...) for this. This could set the door open for SQL injection attacks.
sorry brokenglass, my question doesn't make sense. what I mean is, lets say I have string s = "I am a good boy, and I have a goodmanner". When I use s.Replace("good", "bad") and result "I am a bad boy, and I have a badmanner". Result that I want is "I am a bad boy, and I have a goodmanner". Thanks for the reply :)
2

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;
  }
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.