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?

João Reis
  • 73
  • 5
  • 3
    Always use parameters, and specify the length of your database column in `Add()`. http://bobby-tables.com/csharp – Dan Wilson Jul 26 '18 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.* – Ken White Jul 26 '18 at 22:33
  • 1
    Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Jul 26 '18 at 23:02
  • `should i put the same size as i have the database field itself?`. Yes. – mjwills Jul 26 '18 at 23:02

0 Answers0