There are several questions about using .Net DateTime in Sql statements, but none of them solved my problem.
I use the following code to query an Oracle database:
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; }
But this does not work correctly. When trying to code like this:
DataTable result = QueryByIdAndDate("12345", DateTime.Now, DateTime.Now.AddDays(1));
It gives the following error: ORA-01847: the day of the month must be from 1 to the last day of the month.
I assume this is due to the way DateTime is formatted, but I don't know how to fix it in a reliable way.
source share