Do I need to use parametrized queries when calling ExectureStoreQuery to avoid SQL Injections?

186 Views Asked by At

I'm wondering if I need to use parameterized queries when executing sql from ExecuteStoredProcedure in order to prevent SQL Injection attacks?

According to this MSDN link, I should be using parameters.

According to this other MSDN link, a sql string using {0} is the equivalent of using parameters.

So is it really OK to just have a {0}, {1} etc in my SQL statement:

var rv = _context.ExecuteStoreQuery<int>("select ID from table where typeID = {0}", typeID);

or do I need:

     var param = new SqlParameter("@typeID", SqlDbType.Int);
     param.Value = typeID;
     var rv = _context.ExecuteStoreQuery<int>("select ID from table where typeID = @typeID", param);
1

There are 1 best solutions below

2
On

Basically it boils down to this. Are you reusing the query, with many many calls but with different values for typeID? Then yes it might make a miniscule difference in performance.

On the other hand if you're only making this one call, then majority of the performance hit will be your DB call.

Personally I've yet to see this ever make a tangible difference in any code I've written in the past 8-10 years.

So I vote - don't bother.