admin

DbCommand.Parameters中缺少AddWithValue

sql

我正在构建一个同时处理MSsql和Sqlite的sqlwrapper,到目前为止,使用通用的dbconnection,dataset和dataadapter都没有问题,但是使用dbcommand
parameters.add是唯一的选择。我想像sqlcommand和sqlitecommand一样使用parameter.addwithvalue,但是我不确定如何实现它。

例如,这是我的sqlitefactory:

public class SqlLiteFactory : SqlFactory
{
    public override DbConnection CreateConnection()
    {
        return new SQLiteConnection(ConfigurationManager.ConnectionStrings["ClientDBConnectionString"].ConnectionString);
        //return new SQLiteConnection("Data Source=Resources\\qaqc.sqlite;Version=3");
    }

    public override DataAdapter CreateAdapter(string command, DbConnection connection)
    {
        return new SQLiteDataAdapter(command, connection as SQLiteConnection);
    }

    public override DbCommand CreateCommand()
    {
        return new SQLiteCommand();
    }
}

这是我的实现:

DbConnection c = SqlHandler.Instance.CreateConnection();

DbCommand cmd = SqlHandler.Instance.CreateCommand();

cmd.Connection = c;
cmd.CommandText = "SELECT column FROM table WHERE syncstatus = 0 and UserName = @user GROUP BY column;";
cmd.Parameters.Add("@user");
cmd.Parameters["@user"].Value = SystemInformation.UserName;
DbDataReader dr = cmd.ExecuteReader();

在更具体的sqlcommand和sqlitecommand中,有一个方法.addwithvalue(),这是我希望在父dbcommand类中拥有的方法。


阅读 194

收藏
2021-06-07

共1个答案

admin

用扩展方法解决

static class MyExtensions
    {
        public static void AddParameterWithValue(this DbCommand command, string parameterName, object parameterValue)
        {
            var parameter = command.CreateParameter();
            parameter.ParameterName = parameterName;
            parameter.Value = parameterValue;
            command.Parameters.Add(parameter);
        }
    }

来自http://social.msdn.microsoft.com/Forums/zh-
CN/d56a4710-3fd1-4039-a0d9-c4c6bd1cd22e/dbcommand-parameters-collection-
missing-addwithvalue-method

2021-06-07