delphi连接access数据库示例

菜鸟编程 十五楼的鸟儿 1128浏览 0评论
很简单的一组代码,假设我们有一个名字叫db1.mdb的数据库,里面有一个叫做table1的表。然后代码如下:
[code=delphi]
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, DB, ADODB;

type
TForm1 = class(TForm)
conn: TADOConnection;
Button1: TButton;
DBGrid1: TDBGrid;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
try
self.conn.Close;
self.conn.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+sysutils.ExtractFilePath(application.ExeName)+
'db1.mdb;Persist Security Info=False';
self.conn.Connected:=true;
except on e:exception do
application.MessageBox(Pchar(e.Message),'提示',32);
end;
self.ADOQuery1.Active:=true;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
self.ADOQuery1.Active:=not self.ADOQuery1.Active;
end;

end.[/code]
窗体代码:
[code=delphi]
object Form1: TForm1
Left = 278
Top = 337
Width = 610
Height = 415
Caption = #38142#25509'acc'#31034#20363' Birdol.Com'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = #23435#20307
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
DesignSize = (
602
381)
PixelsPerInch = 96
TextHeight = 12
object Button1: TButton
Left = 32
Top = 16
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object DBGrid1: TDBGrid
Left = 8
Top = 48
Width = 577
Height = 297
Anchors = [akLeft, akTop, akRight, akBottom]
DataSource = DataSource1
TabOrder = 1
TitleFont.Charset = DEFAULT_CHARSET
TitleFont.Color = clWindowText
TitleFont.Height = -12
TitleFont.Name = #23435#20307
TitleFont.Style = []
end
object conn: TADOConnection
ConnectionString =
'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\'#26368#36817'\Delphi'#23567#20363#23376'\lin' +
'kAccess\db1.mdb;Persist Security Info=False'
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 128
end
object ADOQuery1: TADOQuery
Connection = conn
Parameters = <>
SQL.Strings = (
'select * from table1')
Left = 192
Top = 8
end
object DataSource1: TDataSource
DataSet = ADOQuery1
Left = 264
Top = 8
end
end[/code]

转载请注明:鸟儿博客 » delphi连接access数据库示例

游客
发表我的评论 换个身份
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

等待大佬打赏中~