delphi通过format函数设计动态sql语句

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

delphi通过format()函数设计动态sql语句
delphi通过format()函数设计动态sql语句
时间:2011-5-24来源:yang 作者: peng点击: 48次
作者:[美国] Steve Teixeira
改编: doomtoo0(红羽)动态sql是指在运行过程中根据不
同的情况来修改的sql语句。

delphi中TQuery的sql属性编辑器可输入静态的sql语句,当然您可以这样写:
select *from CUSTOMER where COUNTRY=:abcdef;
这样您就可以传参数值实现动态sql查询了。

对于参数化查询来说,delphi可供的方法很多,列如通过params特性或params特性编辑器提供参数值、调用ParamByName()方法提供参数。

下面两个sql语句似乎是都是对的:
SELECT *FROM PART ORDER BY:ORDERVAL;
SELECT *FROM:TABLENAME;
不幸的是,您无法改变sql语句的字段名和表名,那么,如
何使sql语句具有灵活性?这里介绍format()函数来构建sql 语句。

如果您有C或C++编程的经验,您会发现,format()函数与C 中的print()函数很相似.
这里简单介绍format()函数,详细说明请查阅帮助。

使用format()来自定义字符串,需要指定格式化子句。

格式化子句指明在一个给定字符串的何处插入特定类型的字符串。

格式
化子句是由一个百分比符号%和一个类型符组成的。

下面列
出了一些类型符:
c 字符类型
d 整数类型
f 浮点类型
p 指针类型
s 字符串类型
请看下面的例子:
ears
s:=format(‘My name is %s and I‘m %d y
old.‘,[‘Xavier‘,32]);
有两个格式化子句。

%s表示此处插入一个字符串,%d表示此处插入一个整数。

format()函数用一个参数数组给出要替换的值,然后返回结果字符串。

这样,象前面列举的两个sql语句,要构造字段名和表名可变的sql语句,您就可以使用format()函数。

下面给出程序代码(指定字段排序),在type段有程序用到的控件,table1对应与PARTS.DB表。

unit MainFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, DB, DBTables, StdCtrls; type
TMainForm = class(TForm)
dbMain: TDatabase;
lbFields: TListBox;
tblParts: TTable;
dsParts: TDataSource;
dbgParts: TDBGrid;
qryParts: TQuery;
lblFields: TLabel;
procedure FormCreate(Sender: TObject);
procedure lbFieldsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end; var
MainForm: TMainForm; implementation {$R *.DFM} procedure TMainForm.FormCreate(Sender: TObject);
//将字段名列到列表框中
begin
{ Retrieve a list of field names from the PARTS.DB table so that the use can select the field on which to sort the query. These
fields names are placed into a TListBox. }
tblParts.Open;
try
tblParts.GetFieldNames(lbFields.Items);
finally
tblParts.Close;
end;
end; procedure TMainForm.lbFieldsClick(Sender: TObject);
{ 使用format()函数指定排序的字段}
{ Define a constant string from which the SQL string will be
built }
const
SQLString = ‘SELECT * FROM PARTS ORDER BY %s‘; //定义一个常量字符串以供sql语句使用.
begin
with qryParts do
begin
Close; // Make sure the query is closed.
SQL.Clear; // Clear any previous SQL statement.
{ Now add the new SQL statement constructed with the format function }
SQL.Add(Format(SQLString,
[lbFields.Items[lbFields.ItemIndex]]));
//加入用format函数构建的新sql语句.
Open; { Now open Query1 with the new statement } end;
end; end.。

相关文档
最新文档