您的位置:首页 > 编程语言 > Delphi

delphi真接用COM组件连接数据库学习

2005-03-29 16:00 429 查看
此例子需在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来连接其它的数据库了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: