SQL Query works in Workbench but get 'Could not convert variant type' error with the exact same query in Delphi

我们两清 提交于 2019-11-29 15:12:51

Agreeing with SirRufo's comment here. The correct answer to "how do I do this?" is "don't do that; that's the wrong way to do it."

If you stick values directly into the query like that, hackers can find a way to place things into your query that get interpreted as SQL commands. This is known as SQL injection, and it's been responsible for billions of dollars' worth of damage in the last few decades. (Not exaggerating.)

The right way to do it is by cleanly separating your SQL code from your data, by using parameters, like so:

ADOQuery1.SQL.Clear;

//: before an identifier specifies a parameter
ADOQuery1.SQL.Add('SELECT tbl.emailAddress, tbljob.Time FROM '+
  'dbwindowwash.tblclient, dbwindowwash.tbljob, dbwindowash.tbljobclientworker '+
  'WHERE tbljobclientworker.jobID = tbljob.jobID AND '+
  'tbljobclientworker.clientID = tblclient.clientID AND tbljob.Date = :date';

//parse the query and find parameter declarations
ADOQuery1.Prepare;

//set a value for the parameter
ADOQuery1.ParamByName['date'].AsDateTime := TodaysDate;

ADOQuery1.Open

The exact syntax for how to set the value of a parameter may differ from one dataset type to another, but that should give you the basic idea.

If you want a date to work correctly in an SQL query don't go hobbying yourself but use the following format: yyyymmdd.

For instance april 3 2014 becomes: 20140403.

You do this easily with FormatDateTime, in your case:

TodaysDate := FormatDateTime('yyyymmdd', Date)

This date notation is iso compliant and you don't have to think about local settings anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!