此例子需在User中引入ComObj
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComObj, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Rs, Conn: Variant;
SqlStr, ConnStr: string;
{const
adCmdText = $00000001;
adOpenStatic = $00000003;
adUseClient = $00000003;
adLockOptimistic = $00000003;}
begin
SqlStr := 'Select * From mytest';
ConnStr := 'Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=MyCAI;Data Source=VSUN';
Rs := CreateOleObject('ADODB.RecordSet');
Conn := CreateOleObject('ADODB.Connection');
Conn.open(ConnStr);
Rs.ActiveConnection := Conn; //此句比较关键,如果没有此句,那么RS为只读状态
Rs.open(SqlStr, Conn, 3, 3, 1);
// Rs.open(SqlStr, Conn, adOpenStatic, adLockOptimistic, adCmdText); rs打开的另一种型式
showmessage(Rs.fields['age'].type);
showmessage(Rs.fields['age'].value);
// Rs.addnew; 打开时即表示为数据库加入新记录
Rs.fields['myname'].value := 'abcdef';
Rs.fields['age'].value := StrToDate(formatdatetime('yyyy-mm-dd', now()));
Rs.update;
Rs.close;
end;
end.
此例子中是不用delphi中的组件来连接数据库,与ASP中的方法大同小异,其中很多地方需要参考ADODB的手册的。
当然,如果将ConnStr的值改为其它的数据库联接字符串,将可以用ADODB来连接其它的数据库了!