这几天被“Prepare”这个东西搞死了,虽然用它解决了目前的问题,但是完全不知道为什么,如有大侠知道还望指教,不胜感激!
首先,说下开发环境:
win10 x64(1709 [10.0.16299.125]) + Delphi XE7 up1(自带FireDAC) + Firebird 3.0.2.32703_0(数据库字符集使用UTF8)
- 问题一:中文模糊查询
var CompanyType: Integer
FDQuery1.Close;
FDQuery1.SQL.Text := 'SELECT * FROM companyinfo ' +
'WHERE (tag = 0) AND (companytype = :companytype) AND ' +
'((companyname LIKE :Text) OR (pym LIKE :Text))' +
' ORDER BY TIMES DESC';
//FDQuery1.Prepare; //写在这里会报错,提示如下,大致意思是:
//数据库 companytype 字段是SmallInt类型,却赋了一个Integer类型的值
{---------------------------
[FireDAC][Phys][FB]-338. Param [COMPANYTYPE] type changed from [ftSmallInt] to [ftInteger].
Query must be reprepared.
Possible reason: an assignment to a TFDParam.AsXXX property implicitly changed the parameter data type.
Hint: use the TFDParam.Value or appropriate TFDParam.AsXXX property.
---------------------------
}
FDQuery1.ParamByName('companytype').AsInteger := CompanyType;
FDQuery1.Prepare; //必须!而且只能在这里!否则不支持中文模糊查询
FDQuery1.ParamByName('Text').AsString := '%' + btnedtKeyWord.Text + '%';
FDQuery1.Open();
- 问题二:RecordCount 和 Eof
//这是有问题的
FDQuery1.SQL.Text := 'select TAG from truckinfo where (TAG in (0,1)) and (PLATENUM = :PlateNum)';
FDQuery1.Prepare; //必须!否则 RecordCount 始终为 0,而 Eof 始终为 True
FDQuery1.ParamByName('PlateNum').AsString := PlateStr;
FDQuery1.Open;
if FDQuery1.RecordCount > 0 then //或者是 if not FDQuery1.Eof then
begin
...
end;
//---------------------------------------------------------------------
//但是在其它地方都是正常的
//例1
FDQuery1.SQL.Text := 'SELECT * FROM clientinfo WHERE (tag = 0) AND (id = :id)';
FDQuery1.ParamByName('id').AsInteger := AID;
FDQuery1.Open();
if FDQuery1.Eof then
begin
...
end;
//例2
FDQuery1.SQL.Text := 'SELECT * FROM employee WHERE tag <= 0 ORDER BY id';
FDQuery1.Open();
while not FDQuery1.Eof do
begin
...
end;
虽然两个问题目前都解决了,而且可以很好的正常运行,但是完全不知道为什么,尤其是问题二。
最近又遇到了另一种类似的问题,不过规律好像也发现了,就是:参数有中文字段的话,必须使用Prepare
才能正常查询到结果,而且Prepare必须在中文字段参数之前。