简体   繁体   中英

MS Access Query using c#

I am executing a MS Access Query through c#. Below is the query

String SelWHQuery = "SELECT  DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours" + 
    "' WHERE EMPID = '" + Eno + 
    "'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + 
    "# FROM  INOUTPunching";

which is giving below error

{"The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."}

I need to know:

  1. Why is this not working?
  2. Is there any simplier method?

You should place the FROM clause before the WHERE clause. That is the problem with your query. And you have an extra single quote which should be removed. This is the query you should write:

String SelWHQuery = "SELECT  DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM  INOUTPunching " + 
" WHERE EMPID = '" + Eno + 
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";

And about a simpler method: no, this is the simplest method but it is prone to SQL injection attacks. Replace it with a parameterized query (assuming you have an OldDbCommand name cmd ):

String SelWHQuery = "SELECT  DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM  INOUTPunching " + 
" WHERE EMPID = @EmpId AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";

cmd.CommandType = CommandType.Text;
cmd.CommandText = SelWHQuery;
cmd.Parameters.AddWithValue("@EmpId", Eno);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM