[C++Builder/Delphi初學者指南] 三分秒完成數據表的轉換
西安 warton
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
筆者在先前寫程序時,經常遇到數據庫的轉換問題,一般的方法是用SQL語句將數據從表中取出,再insert到另一個表。這個方法比較通用,在任何編程語言中都可以使用。但這樣比較麻煩,需要編程者有一定的經驗。
筆者在使用C++Builder和Delphi之後,發現它們提供的BatchMove控件就能完成數據表的轉換。而且操作相當方便,在數分鐘之內就能完成!
下面,我來做一個實驗:將BCDEMOS(Paradox庫,CB,Delphi自帶)中的Customer.db轉換爲test.Mdb(MicroSoft ACCESS庫)中的test(表)。
1. 建立一個新工程,選擇New-àApplication;
2. 添加控件:Table1,Tabel2,DataSource1, DataSource2,DBGrid1, DBGrid2,BatchMove1,Button1,Button2
3. 建立一個MDB文件,打開該文件,建立一個新表,字段只寫一個Custno,類型爲數字(這裏使用的是ACESS的MDB文件數據庫,字段不用和paradox表一致,只要第一個字段相同就行,或者只要有一個空表就行),併爲該文件配置ODBC。筆者這裏是D:/test.mdb(筆者的odbc dsn設置爲access,數據庫爲:D:/test.mdb,如下圖:)。<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />
4. 在C++Builder/Delphi的SQL Explorer中new 一個數據庫別名:ACCESS,並選擇其odbc dsn爲剛纔設置的ODBC數據源。
5. 分別爲各控件設置屬性(只需在控件上設置即可,不用在代碼中寫了):
Table1 |
Table1: TTable Active = True DatabaseName = 'BCDEMOS' TableName = 'customer.db' |
Table2 |
Table2: TTable DatabaseName = 'ACCESS' TableName = 'test' TableType = tDefault |
DataSource1 |
DataSource1: TDataSource DataSet = Table1 |
DataSource2 |
DataSource2: TDataSource DataSet = Table2 |
BatchMove1 |
BatchMove1: TBatchMove Destination = Table2 Mode = batCopy //很重要,表明是複製模式 Source = Table1 |
DBGrid2 |
DBGrid2: TDBGrid DataSource = DataSource1 |
DBGrid1 |
DBGrid1: TDBGrid DataSource = DataSource2 |
Button1 |
Button1: TButton Caption = '轉換' |
Button2 |
Button2: TButton Caption = '刷新' |
6.爲Button1及Button2添加事件:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
BatchMove1->Execute();//執行轉換
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Table2->Open(); //打開表,可以在DBGrid2中看到轉換的結果
}
最後,編程並運行程序,點擊Button1等程序執行完畢後,點擊Button2,你會發現Paradox庫中的Customer.db中的數據全都導入到了ACCESS庫 test.mdb的test表中了。
使用這種方法操作相當簡單,只需要簡單地設置幾個相關的性就OK了,有興趣的朋友不妨試試。(本測試程序在windows XP Home Edition ,C++Builder 6下完成)