unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    ADOConnection1: TADOConnection;
    ADODataSet1: TADODataSet;
    ADOCommand1: TADOCommand;
    Panel1: TPanel;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//添加
procedure TForm1.Button1Click(Sender: TObject);
begin
  try
    ADOCommand1.CommandText := 'INSERT INTO country VALUES("AAA", "BBB", "CCC", 111, 222)';
    ADOCommand1.Execute;

    ADOCommand1.CommandText :=
      'INSERT INTO country(Name,Capital,Continent) VALUES("XXX", "YYY", "ZZZ")';
    ADOCommand1.Execute;
  except on E: Exception do
    ShowMessage(E.Message);
  end;

  Button4.Click;
end;

//更新
procedure TForm1.Button2Click(Sender: TObject);
begin
  ADOCommand1.CommandText := 'UPDATE country SET Area=123,Population=456 WHERE Name="AAA"';
  ADOCommand1.Execute;

  ADOCommand1.CommandText := 'UPDATE country SET Capital="MMM" WHERE Capital="YYY"';
  ADOCommand1.Execute;

  Button4.Click;
end;

//删除
procedure TForm1.Button3Click(Sender: TObject);
begin
  ADOCommand1.CommandText := 'DELETE * From country WHERE Name="AAA"';
  ADOCommand1.Execute;
  ADOCommand1.CommandText := 'DELETE * From country WHERE Name="XXX"';
  ADOCommand1.Execute;

  Button4.Click;
end;

//查看
procedure TForm1.Button4Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT * FROM country';
    Open;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  mdbFile: string;
begin
  {因要修改数据库, 特复制了一份}
  mdbFile := mdbFile + 'C:\Temp\dbdemos.mdb';

  ADOConnection1.ConnectionString :=
  'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + mdbFile + ';Persist Security Info=False';

  ADOConnection1.LoginPrompt := False;
  ADOConnection1.Open; //ADOConnection1.Connected := True;

  ADODataSet1.Connection := ADOConnection1;
  ADOCommand1.Connection := ADOConnection1;

  DBGrid1.DataSource := DataSource1;
  DataSource1.DataSet := ADODataSet1;
end;

end.

posted on 2009-05-28 23:10  万一  阅读(7575)  评论(25编辑  收藏  举报