好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

c# – IDbCommand MySQL和SQL Server的命名参数

我一直在尝试创建一些DB独立代码,如下所示:

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

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

适用于mysql的命令文本是:

select * from mytable where field1 = ?param1

适用于sqlserver的命令文本是:

select * from mytable where field1 = @param1

是否有某种形式适用于两者?

编辑:

> SQL Server 2008R2

> MySQL 5.0.X

不,我认为没有这样的方法.所以你必须提供自己的:

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;
}

用法:

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

或者您可以使用this扩展,它使用反射来使用DbCommandBuilder类中的受保护方法GetParameterName:

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);
    }
}

然后它很简单:

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

查看更多关于c# – IDbCommand MySQL和SQL Server的命名参数的详细内容...

  阅读:47次