需要安装 MyODBC 数据库驱动,常见的版本是 3.51,比如 MyODBC-3.51.11-2-win.exe。
代码示例:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, Grids, DBGrids, StdCtrls;
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button1: TButton;
procedure FormActivate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormActivate(Sender: TObject);
begin
try
ADOConnection1.ConnectionString:=('DRIVER={MySQL ODBC 3.51 Driver};'+
'SERVER=localhost;'+
'DATABASE=17kf8;'+
'USER=root;'+
'PASSWORD=mbi1001;'+
'OPTION=3;');
ADOConnection1.Close;
ADOConnection1.Open;
except
application.MessageBox('无法连接到MySQL数据库', '提示', MB_ICONINFORMATION);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ADOQuery1.close;
ADOQuery1.SQL.Text := 'SET NAMES gbk;';
ADOQuery1.ExecSQL();
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('SELECT * FROM open_news');
ADOQuery1.Open;
end;
end.
关键代码解释:
1,DRIVER={MySQL ODBC 3.51 Driver}; 是连接 MySQL 数据库的关键;
2,ADOQuery1.SQL.Text := 'SET NAMES gbk;' 语句避免了 MySQL 的汉字乱码。
作者:张庆(网眼) 西安 PHP 教育培训中心 2010-10-3
来自“网眼视界”:http://blog.why100000.com
作者微博:http://t.qq.com/zhangking
“十万个为什么”电脑学习网:http://www.why100000.com