关于在 Sql 语句中使用 .Net DateTime 有几个问题,但没有一个能解决我的问题。
我正在使用以下代码查询 Oracle 数据库:
private DataTable QueryByIdAndDate(string id, DateTime fdate, DateTime tdate) {
string query = "SELECT * FROM table WHERE ID = :id AND DATE_TIME BETWEEN :from AND :to"
DbCommand cmd = db.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
DbParameter fromDate = CreateDateParameter(cmd, fdate);
fromDate.ParameterName = "from";
DbParameter toDate = CreateDateParameter(cmd, tdate);
toDate.ParameterName = "to";
DbParameter idParam = CreateStringParameter(cmd, id);
idParam.ParameterName = "id";
cmd.Parameters.AddRange(new DbParameter[] { fromDate, toDate, idParam });
return db.ExecuteQuery(cmd);
}
private DbParameter CreateDateParameter(DbCommand cmd, DateTime date) {
DbParameter param = cmd.CreateParameter();
param.DbType = DbType.DateTime;
param.Direction = ParameterDirection.Input;
param.Value = date;
return param;
}
但它不能正常工作。像这样尝试代码时:
DataTable result = QueryByIdAndDate("12345", DateTime.Now, DateTime.Now.AddDays(1));
它给出了以下错误: ORA-01847: day of month must be between 1 and last day of month
我假设它与 DateTime 的格式化方式有关,但我不知道以可靠方式解决此问题的正确方法。