Joakim Carlsson
Joakim Carlsson

Reputation: 1580

Parameters.AddWithValue does not replace my value

Trying to run a SQL query and I were told to use Parameters to avoid SQLInjection. So I'm playing around with parameterized query. But it's not going so good.

This is my code:

using (_cmd = _connection.CreateCommand())
{
    _connection.Open();
    _cmd.CommandText = "SELECT * FROM `users` WHERE `username`= '@username'";
    _cmd.Parameters.AddWithValue("@username", _username);
}

As I understand it @username will be replaced with my username field. But this is not the case, not sure what I am doing wrong.

Upvotes: 1

Views: 1007

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172568

Remove the quotes from '@username' else it will be treated as a string literal.

_cmd.CommandText = "SELECT * FROM `users` WHERE `username`= @username";

Upvotes: 3

Grant Winney
Grant Winney

Reputation: 66479

You've turned the parameter into a string literal in your query.

Remove the apostrophes from around @username:

_cmd.CommandText = "SELECT * FROM `users` WHERE `username`= @username";

Upvotes: 4

Related Questions