一個簡單的Delphi7小程序,使用MySql數據庫做簡單查詢,用DBGrid控件顯示結果,實現過程如下:
(1)在MySql中新建demouser表,插入記錄用于測試。
(2)在Delphi7中新建項目。
(3)在From中添加組件。
組件Panel:pnl1
組件屬性-屬性值:
Caption-請輸入工號:
組件Edit:edt1
組件Button:btn1
組件屬性-屬性值:
Caption-查詢
組件ADOQuery:qry1
組件屬性-屬性值:
Active-True //設置SQL屬性后取得表中數據,綁定的顯示控件上可以實時出現數據
ConnectionString-Provider=MSDASQL.1;Persist Security Info=False;Data Source=MySqlOdbcU //ODBC方式連接MySql,參考:http://blog.csdn.net/akof1314/article/details/6822902
SQL-SELECT * FROM DEMOUSER;
組件DataSource:ds1
組件屬性-屬性值:
DataSet-qry1 //綁定數據集ADOQuery
組件DBGrid:dbgrd1 //認的情況下,dbgrid的數據修改就和打開數據庫直接修改一樣,修改完自動保存,除非修改了readonly(只讀) enable(可選中)這些屬性的默認值或者單獨修改了字段的這兩個屬性
組件屬性-屬性值:
DataSource-ds1 //綁定數據源DataSource
Enabled-True //可選中?
ReadOnly-True //只讀?
(4)在代碼編輯窗口中增加代碼。
unitDataInMysql;interface
usesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ADODB,ComObj, Grids, DBGrids, ExtCtrls;typeTForm1= class(TForm)
qry1: TADOQuery;
ds1: TDataSource;
btn1: TButton;
dbgrd1: TDBGrid;
pnl1: TPanel;
edt1: TEdit;procedurebtn1Click(Sender: TObject);private
{Private declarations}
public
{Public declarations}
end;varForm1: TForm1;implementation
usesUserMessage;{$R *.dfm}
procedureTForm1.btn1Click(Sender: TObject);vars:string;begins:='SELECT * FROM DEMOUSER where 1=1';if edt1.Text<>'' then
begins:=s+'and id='+edt1.Text;end;with qry1 do
beginClose;
SQL.Clear;
SQL.Add(s);
Open;end;end;end.
(5)運行項目,保存文件。
效果如下:
注意:選擇【Project | View Source】,可以創建一個缺省的Delphi項目文件的源代碼(.DPR),修改后雙擊它打開對應的項目,避免點擊啟動時總是啟動其他項目。
programProject3;usesForms,
DataInMysqlin 'DataInMysql.pas' {Form1}; //改這兒{$R *.res}
beginApplication.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;end.