Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating SQL queries safely in C#

Tags:

c#

sql

What's the safest way of generating SQL queries in C#, including cleansing user input so it's safe from injection? I'm looking to use a simple solution that doesn't need external libraries.

like image 495
Dan Stevens Avatar asked Feb 24 '12 15:02

Dan Stevens


Video Answer


1 Answers

Use Sql Parameters:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v=vs.80).aspx

Here's an example in C#

SqlCommand tCommand = new SqlCommand();
tCommand.Connection = new SqlConnection("YourConnectionString");
tCommand.CommandText = "UPDATE players SET name = @name, score = @score, active = @active WHERE jerseyNum = @jerseyNum";

tCommand.Parameters.Add(new SqlParameter("@name", System.Data.SqlDbType.VarChar).Value = "Smith, Steve");
tCommand.Parameters.Add(new SqlParameter("@score", System.Data.SqlDbType.Int).Value = "42");
tCommand.Parameters.Add(new SqlParameter("@active", System.Data.SqlDbType.Bit).Value = true);
tCommand.Parameters.Add(new SqlParameter("@jerseyNum", System.Data.SqlDbType.Int).Value = "99");

tCommand.ExecuteNonQuery();
like image 150
Guillaume86 Avatar answered Sep 28 '22 06:09

Guillaume86