无法向OleDbCommand添加参数

时间:2017-01-18 16:07:04

标签: c# sql oledb oledbcommand

我有这样的代码:

using (DbCommand command = factory.CreateCommand())
{
    command.Connection = connection;
    command.CommandText = string.Format("SELECT {0} FROM {1} WHERE {2} >= ? AND {2} <= ?",
            selectColumns,
            TableName,
            TimeStampColumn);

    var startTimeParam = command.CreateParameter();

    startTimeParam.ParameterName = "@StartTime";
    startTimeParam.DbType = DbType.DateTime;
    startTimeParam.Value = StartDate;

    var endTimeParam = command.CreateParameter();
    endTimeParam.ParameterName = "@EndTime";
    endTimeParam.DbType = DbType.DateTime;
    endTimeParam.Value = EndDate;

    DbDataAdapter adapter = factory.CreateDataAdapter();
    adapter.SelectCommand = command;
    adapter.SelectCommand.Parameters.Add(startTimeParam);
    adapter.SelectCommand.Parameters.Add(endTimeParam);

    adapter.Fill(table);
}

但是我无法设置select命令的参数。我尝试使用@StartTime@EndTime代替?,但我收到了消息Must declare scalar variable @StartTime

当我使用?代替@StartTime@EndTime时,我没有收到任何结果。

只有当我将所有变量都放在String.Format()函数中时它才有用,但我不想使用就是这样。

0 个答案:

没有答案