IDbCommand named parameters for both MySQL and SQL Server

I am trying to create some DB-independent code, for example:

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

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

The text of the command that works for mysql:

select * from mytable where field1 = ?param1

Command text that works for sqlserver:

select * from mytable where field1 = @param1

Is there some form that will work for both?

EDIT:

  • SQL Server 2008R2
  • MySQL 5.0.X
+4
source share
2 answers

No, I think there is no such method. Therefore, you must 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;
}

Using:

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

Or you can use the this extension , which uses reflection to use the method protected GetParameterNamefrom the class DbCommandBuilder:

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 is simple:

param1.ParameterName = connection.GetParameterName("param1");
+1

:

select * from mytable where field1 = @param1

MySql .

0

All Articles