Chris Klepeis
Chris Klepeis

Reputation: 9983

C# Assembly Injection Check

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

Upvotes: 1

Views: 1004

Answers (2)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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";

Upvotes: 3

Quassnoi
Quassnoi

Reputation: 425341

Use bound parameters:

SqlCommand cmd = new SqlCommand(myQuery, conn);
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar, 10, lastName);

Upvotes: 7

Related Questions