博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

TADOCommand

Posted on 2011-08-19 17:25  豪杰的爸爸  阅读(865)  评论(0编辑  收藏  举报

 

TADOCommand执行CommandText属性中的SQL命令。通过属性Connection设置连接数据库的TADOConnection对象,也可以通过ConnectionString属性设置参数连接数据库。
  TADOCommand可以执行DDL和DML语句。如果执行Select,则使用TADODataSet, TADOQuery或者TADOStoredProc则更好。

  执行TADOCommand对象中的SQL语句,使用方法Execute。

(1) CommandText属性

  SQL语句文本,例如:
  ADOCommand1.CommandText := 'select * from DCPost';

一个带参数的例子:

procedure TForm1.Button1Click(Sender: TObject);
begin
 if not ADOConnection1.Connected then
   ADOConnection1.Open ;
 try
   DOCommand1.Connection := ADOConnection1 ;
   ADOCommand1.CommandText :='insert into DCPost values   (:sPostNo,:sPostName,0)';
   ADOCommand1.Parameters.ParamByName('sPostNo').Value :='100';
   ADOCommand1.Parameters.ParamByName('sPostName').Value :='工程师';
   ADOCommand1.Execute;
 except
   ADOCommand1.Cancel;
   application.MessageBox('检索数据出错','提示错误');
 end;
end;
(2) CommandType属性
  指明CommandText中的命令类型属性,可以取下面的值:
  CmdText:SQL查询文本    CmdFile:文件   CmdTable:数据库表
  CmdStoredProc:存储过程  CmdUnknown:未知类型(缺省)
  CmdTableDirect:直接打开的数据库表
    使用CmdTable例子。由于返回一个数据集,使用TADODataSet对象来接收。
procedure TForm1.Button2Click(Sender: TObject);
begin
  if not ADOConnection1.Connected then ADOConnection1.Open ;
  try
    ADOCommand2.Connection := ADOConnection1 ;
    ADOCommand2.CommandText :='DCNation';
    ADODataSet1.Recordset := ADOCommand2.Execute;
  except
    ADOCommand1.Cancel;
    application.MessageBox('插入数据出错','提示错误');
  end;
end;

(3) Execute方法
    该方法返回一个数据集,对于DDL和非Select语句,则返回一个空集。如果返回的是一个数据集,则必须使用TADODataSet对象来接收。
   function Execute: _Recordset; overload;
   function Execute(const Parameters: OleVariant): _Recordset; overload;
   function Execute(var RecordsAffected: Integer; const Parameters: OleVariant): _RecordSet; overload;