0

I've been looking for an answer to my question, but i cannot find it, so here it is:

Between String.Format and MySql Parameters, what is the best practice in terms of creating a query for the database.

Here is how i'm using them:

String.Format

string query = String.Format(@"SELECT * FROM users WHERE id = {0}", id);

MySql Parameters

MySqlCommand dbCommand = new MySqlCommand(@"SELECT * FROM users WHERE id = @id");
dbCommand.Parameters.Add("@id", MySql.Data.MySqlClient.MySqlDbType.Int32, 50).Value = id;

If the parameters way is the best practice, i have another question, one of the parameters of the Add function is the size, in the example above is the "50", should i put the same size as i have the database field itself?

4
  • 3
    Always use parameters, and specify the length of your database column in Add(). bobby-tables.com/csharp Commented Jul 26, 2018 at 22:29
  • 1
    There are literally hundreds of questions here about concatenating text for SQL, and every one of them most likely has an answer or comment that says Don't concatenate text for SQL. Use parameters instead. It handles quotes around things when needed, puts dates in the proper format, and prevents SQL injection. Commented Jul 26, 2018 at 22:33
  • 1
    Possible duplicate of What are good ways to prevent SQL injection? Commented Jul 26, 2018 at 23:02
  • should i put the same size as i have the database field itself?. Yes. Commented Jul 26, 2018 at 23:02

0

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.