建立、改變及重構(gòu)Access數(shù)據(jù)庫(kù)

字號(hào):

由vb提供的datamanager對(duì)于開(kāi)發(fā)人員來(lái)講并不是一件強(qiáng)大的工具。對(duì)于那些沒(méi)有裝access數(shù)據(jù)庫(kù)的人來(lái)說(shuō),在開(kāi)發(fā)時(shí)建立.改變或重構(gòu)數(shù)據(jù)庫(kù),以及載入/重載表單都是一件痛苦的事。此外datamanager不能讓我們打印數(shù)據(jù)庫(kù)的結(jié)構(gòu)。
    讓我們編一個(gè)小程序?qū)崿F(xiàn)上述功能,然后工程結(jié)束后把它拋棄.
    首先可以用一個(gè)以逗號(hào)分隔的文本文件來(lái)儲(chǔ)存表結(jié)構(gòu),如下面這個(gè)人員表。
     lpersonid,long,,person’s id
     spersonfirstname,text,20,person’s first name
     spersonlastname,text,20,person’s last name
     bisafunperson,boolean,,invite to a party?
     itypeofjob,integer,,0=none 1=manual 2=office 3=programmer etc.
     iage,integer,,person’s age
    該表有六列,每列獨(dú)占一行。每行中用逗號(hào)分隔下列各項(xiàng):字段名.字段類(lèi)型.字段長(zhǎng)度(如果不是字符型字段,就留空,僅用逗號(hào)分隔)及字段描述。如果你想在字段描述中使用逗號(hào),你可以不用逗號(hào)分隔各項(xiàng),
    換成tab分隔。
    一個(gè)通用程序能讀取這些文件并根據(jù)它們建立起數(shù)據(jù)庫(kù)。這種方法,連同一些通用的導(dǎo)入/導(dǎo)出程序能大大加快程序開(kāi)發(fā)的速度。舉例 來(lái)說(shuō),你不能在dm中刪除一個(gè)表的一列,但通過(guò)刪除csv文件中對(duì)一列的定義,然后重新運(yùn)行構(gòu)建數(shù)據(jù)庫(kù)的程序,你就能輕松做到這一點(diǎn)。
    如果你想打印出數(shù)據(jù)庫(kù)的結(jié)構(gòu),方法也很簡(jiǎn)單:用excel讀csv文件,再將其粘貼到word中,這樣你就可以打印出整個(gè)數(shù)據(jù)庫(kù)的結(jié)構(gòu)了。
    下面是程序代碼:
     sub createtable (sdatabasename as string, scsvfilename as string,
     stablename as string)
     dim itemp as integer
    ’將控制權(quán)交還給操作系統(tǒng),使其在創(chuàng)建數(shù)據(jù)庫(kù)的同時(shí)能運(yùn)行其它程序-別讓你的計(jì)算機(jī)閑著!
     itemp = doevents()
    ’創(chuàng)建一個(gè)300x3數(shù)組
     redim stables(300, 3) as string
     dim sdatatypeline as string
    ’ 讀取csv文件,并將字段定義保存在數(shù)組中
     call readtabledefinition(scsvfilename, stables())
     dim tbl as new tabledef
     dim fld as field
    ’打開(kāi)數(shù)據(jù)庫(kù)
     dim dbpersons as database
     set dbpersons = opendatabase(sdatabasename & ".mdb", true)
    ’記錄下新的表單名
     tbl.name = stablename
    ’增添第一個(gè)字段
     set fld = new field
     fld.name = stables(1, 1)
     fld.type = getfieldtype((stables(1, 2)))
     fld.size = val(stables(1, 3))
     tbl.fields.append fld
     dbpersons.tabledefs.append tbl
    ’增加其它的字段
     dim inextcol as integer
     inextcol = 1
     do while true
     set fld = new field
     inextcol = inextcol + 1
    ’到了表定義的底部則退出
     if stables(inextcol, 1) = "***end***" then
     exit do
     end if
     fld.name = s