在下面这个delphi连接以及操作mysql数据库中,我们以最简单展示,没有考虑异常等情况,我在其中加了两个按钮,一个是连接数据库,一个是从连接的数据库查询一个数据,
源码下载地址:http://download.csdn.net/detail/cq20110310/6854069
mysql:表student,字段name
unit uTest1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DB, ADODB, StdCtrls;
type
TFormDB = class(TForm)
btn1: TButton;
Button1: TButton;
ADOConn: TADOConnection;
ADOQuery:TADOQuery;
procedure btn1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormDB: TFormDB;
implementation
{$R *.dfm}
procedure TFormDB.btn1Click(Sender: TObject);
var
strConn:string;
begin
ADOConn:=TADOConnection.Create(Self);
strConn:='DRIVER={MySQL ODBC 5.1 Driver};SERVER=127.0.0.1;DATABASE=delphi_test1;UID=root;PASSWORD=OMSDB;OPTION=3;PORT=3306;';
ADOConn.ConnectionString:=strConn;
ADOConn.Open;
if ADOConn.Connected then
begin
ShowMessage('连接数据库成功');
end
else
begin
ShowMessage('连接数据库失败');
end;
end;
procedure TFormDB.Button1Click(Sender: TObject);
var
strSQL:string;
begin
ADOQuery:=TADOQuery.Create(Self);
ADOQuery.Connection:=ADOConn;
strSQL:='select * from student ';
ADOQuery.SQL.Add(strSQL);
ADOQuery.Open;
ShowMessage(ADOQuery.FieldByName('name').AsString);
end;
end.