4

I've been trying to create some DB independent code like the following:

IDbCommand command = connection.CreateCommand();
command.CommandText = "...";

IDbDataParameter param1 = command.CreateParameter();
param1.ParameterName = "param1";
param1.Value = "value";
command.Parameters.Add(param1);

The command text that works for mysql is:

select * from mytable where field1 = ?param1

The command text that works for sqlserver is:

select * from mytable where field1 = @param1

Is there some form that will work for both?

EDIT:

  • SQL Server 2008R2
  • MySQL 5.0.X
Andres A.
  • 1,329
  • 2
  • 21
  • 37

2 Answers2

1

No, i think there's no such method. So you have to provide your own:

public static String GetProviderParameter(string paramName, IDbConnection con)
{
    string prefix = "";
    if(con is System.Data.SqlClient.SqlConnection)
        prefix = "@";
    else if(con is System.Data.OleDb.OleDbConnection)
        prefix =  "?";
    else if(con is System.Data.Odbc.OdbcConnection)
        prefix =  "?";
    else if(con is MySql.Data.MySqlClient.MySqlConnection)
        prefix =  "?";

    return prefix + paramName;
}

Usage:

param1.ParameterName = GetProviderParameter("param1", connection);

Or you could use this extension which uses reflection to use the protected method GetParameterName from the DbCommandBuilder class:

public static class Db
{
    static readonly Func<DbConnection, DbProviderFactory> getDbProviderFactory = 
        (Func<DbConnection, DbProviderFactory>)Delegate.CreateDelegate(typeof(Func<DbConnection, DbProviderFactory>), typeof(DbConnection).GetProperty("DbProviderFactory", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true));
    static readonly Func<DbCommandBuilder, string, string> getParameterName =
        (Func<DbCommandBuilder, string, string>)Delegate.CreateDelegate(typeof(Func<DbCommandBuilder, string, string>), typeof(DbCommandBuilder).GetMethod("GetParameterName", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(string) }, null));

    public static DbProviderFactory GetProviderFactory(this DbConnection connection)
    {
        return getDbProviderFactory(connection);
    }

    public static string GetParameterName(this DbConnection connection, string paramName)
    {
        DbCommandBuilder builder = GetProviderFactory(connection).CreateCommandBuilder();

        return getParameterName(builder, paramName);
    }
}

Then it's simple as:

param1.ParameterName = connection.GetParameterName("param1");
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can use this for both:

select * from mytable where field1 = @param1

See the documentation for MySql here.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232