I have the following function:
public DataTable GetRecordSet(String query, string[] parameters)
It is typically used as follows:
DataTable dt = GetRecordSet( "select * from objects where ob_id = @obid and ac_id = @acid", new[] { objectId, accountId });
The GetRecordSet method parses the query parameter looking for words preceded by @ and create appropriate SqlParameter objects that’s passed into a SqlCommand object. In this case, two parameters would be created.
The query parameter will be always be supplied by me, the parameters array may have data from the user.
I am concerned that because I’m generating the parameter names from a string, that I may somehow be inadvertently circumventing anti-SQL injection countermeasures. Is this method safe?
Update:
GetRecordSet gets a select command as follows:
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = GetSqlCommand(query, parameters);
The GetSqlCommand method:
private SqlCommand GetSqlCommand(string query, string[] parameters)
{
SqlCommand sq = new SqlCommand(query, myConnection);
// enum parameters
// get name of parameter from the query string and add it to the SqlCommand
SqlParameter p;
string[] paramNames = query.Split('@');
string name;
int paramCounter = 0;
if (parameters != null)
{
foreach (string param in parameters)
{
paramCounter += 1;
if (param != "")
{
try
{
if (paramNames.Length > paramCounter)
{
name = paramNames[paramCounter].Split(' ')[0];
p = new SqlParameter(name, param);
sq.Parameters.Add(p);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex);
}
}
}
}
return sq;
}
The code above is safe from SQL Injection – there is a way to exploit parameter names, but this code is safe from that particular issue.
Of course there is no way to be 100% certain, but this is as good as it gets.