Question

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

Was it helpful?

Solution

Use bound parameters:

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

OTHER TIPS

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";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top