> Unfortunately, the factory model in 2.0 does not do anything for you
> in parameterized query scenarios when you don't know what provider
> you're using ;-(
>
> You're going to have to branch in your code or provide your own
> framework (which is probably more work than you want to do).
Actually, I quickly wrote some methods to handle this issue, and they're
(more or less) working; this code accepts queries in SQL Server format
(using '@Name' for parameters) and rewrites them in order to work wih
different providers; it builds DbCommands on the fly with any number of
parameters.
It uses some members from the class it belongs to, but it should be quite
clear:
----------
protected DbCommand CreateCommand(string query,params DbType[] parameters)
{
DbCommand command = dbconn.CreateCommand();
string[] sections = query.Split('@');
string[] parameternames = new string[sections.Length - 1];
for(int p = 0;p < parameternames.Length;p++)
{
int i;
for(i = 0;i < sections[p + 1].Length;i++)
if(!char.IsLetterOrDigit(sections[p + 1][i]))
break;
parameternames[p] = sections[p + 1].Substring(0,i);
}
switch(dbtype)
{
case DBTypes.SQL:
command.CommandText = query;
break;
case DBTypes.Oracle:
command.CommandText = query.Replace('@',':');
break;
case DBTypes.MySQL:
// Not implemented yet
break;
}
for(int i = 0;i < parameternames.Length;i++)
{
DbParameter parameter = command.CreateParameter();
parameter.ParameterName = parameternames[i];
parameter.DbType = parameters[i];
command.Parameters.Add(parameter);
}
return(command);
}
----------
It can obviously be improved, but it's ok for my needs.
Howewer, it would nice if the framework handled this issue; it should be its
job, since ADO.NET 2.0 tries to provide an abstract data access layer.
Massimo
Mary Chipman [MSFT] - 13 Jan 2006 22:54 GMT
I agree with your conclusion -- it sure would be nice. Just make sure
you guard against SQL injection attacks :-)
--Mary
>> Unfortunately, the factory model in 2.0 does not do anything for you
>> in parameterized query scenarios when you don't know what provider
[quoted text clipped - 64 lines]
>
>Massimo
Massimo - 14 Jan 2006 06:42 GMT
>I agree with your conclusion -- it sure would be nice. Just make sure
> you guard against SQL injection attacks :-)
I'll call that code from *my* application, I don't think I'me going to crack
it ;-)
By the way, do you know some better way to tokenize a text string? I
Split()ted it at every '@' and then manually terminated the substrings at
the first non-letter-or-digit character, but this seems quite horrible code
to me :-/
Massimo