Problems with Oledb and DATETIME
I need help. This is my code:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request " + "WHERE _Date >= " + "@Dt", con);
cmd.Parameters.Add("@Dt", OleDbType.Date);
cmd.Parameters["@Dt"].Value = DateTime.Now;
using (IDataReader reader = cmd.ExecuteReader())
{ }
But it returns an exception:
"Syntax error in query expression '_Date> = @Dt'." OleDb Exception
and with this code:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request " + "WHERE _Date > " + "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +"'", con);
using (IDataReader reader = cmd.ExecuteReader())
{ }
it returns
"Syntax error in query expression '_Date>' 2014-08-08 10:55:04 ''."
What's wrong here?
+3
user886550
source
to share
3 answers
Despite the underscore, the name Date is a reserved word, so you should probably put the field name in parentheses:
WHERE [_Date] > @Dt
Better to avoid reserved words and use a better description for the field name, such as RequestDate. I would also avoid running the underscore column name.
+3
LarsTech
source
to share
try it
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Request] WHERE [_Date] >= @Date", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);
+1
user3834541
source
to share
Instead of subjecting your SQL to injection by concatenating your sql together, use a placeholder for the parameter.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request WHERE _Date > ?", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);
0
Cam bruce
source
to share