views:

548

answers:

2

I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.

Is there a simple function in C# to prevent SQL injection?

For example

string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";

This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?

For example, these probably wont work:

using @dbName;

SELECT * FROM @table

OPEN SYMMETRIC KEY @keyName

etc

+7  A: 

Use bound parameters:

SqlCommand cmd = new SqlCommand(myQuery, conn);
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 10, lastName);
Quassnoi
This would work on standard queries but what if I had to use it for a table name or another situation in which this method would not work?
Chris Klepeis
+3  A: 

Use parameters ....

(This has been posted often already)

string myQuery = "SELECT * FROM myTable WHERE lastname = @p_name";

SqlCommand cmd = new SqlCommand();
cmd.CommandText = myQuery;
cmd.Parameters.Add ("@p_name", SqlDbType.Varchar).Value = "melp";
Frederik Gheysels