user886550
user886550

Reputation: 221

Problems with Oledb and DATETIME

I need some 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?

Upvotes: 3

Views: 1166

Answers (3)

LarsTech
LarsTech

Reputation: 81610

Despite the underscore, the name Date is a reserved word, so you should probably place the field name in brackets:

WHERE [_Date] > @Dt

It's best to avoid reserved words and use a better description for the field name, like RequestDate. I would also avoid starting a column name with an underscore.

Upvotes: 3

user3834541
user3834541

Reputation: 161

Try like this

OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Request] WHERE [_Date] >= @Date", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);

Upvotes: 2

Cam Bruce
Cam Bruce

Reputation: 5689

Instead of exposing your SQL to injection by concatinating 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);

Upvotes: 0

Related Questions