.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

Use parameters instead of string concatenation for forming SQL queries

String concatenation is not a secure approach as clever person can execute unwanted SQL statement by some tricks (SQL injection attack). Use parameters if possible.

Bad code:

    SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM Accounts WHERE Login='" + login + "' AND Password='" + password + "'", conn);

Good code:

    SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM Accounts WHERE Login=@login AND Password=@password", conn);

    SqlParameter param = new SqlParameter("login", SqlDbType.VarChar, 100);

    param.Value = login;

    command.Parameters.Add(param);

    param = new SqlParameter("password", SqlDbType.VarChar, 100);

    param.Value = password;

    command.Parameters.Add(param);



7/20/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.