盡管我們可以通過設(shè)計器來創(chuàng)建數(shù)據(jù)庫, 但是我們也可以在asp的代碼中創(chuàng)建數(shù)據(jù)庫,這里我們就一起來看一下如何在asp中創(chuàng)建數(shù)據(jù)庫.
在ASP中創(chuàng)建數(shù)據(jù)庫,我們需要用到ADOX(Microsoft ADO Extensions for DDL and Security), 這個ADO的擴(kuò)展可以幫助我們創(chuàng)建和修改數(shù)據(jù)庫結(jié)構(gòu)信息, 也包括數(shù)據(jù)庫對象的安全策略. 它隨著ADO 2.1 出現(xiàn), 所以它能夠在大多數(shù)的Windows平臺上工作. 您可以到MS的官方網(wǎng)站去獲取最新的ADO版本,當(dāng)然,里邊包括了ADOX.
創(chuàng)建數(shù)據(jù)庫
在我們開始代碼編寫之前,確定IIS所對應(yīng)的帳號IUSER_[MachineName]
為了順利創(chuàng)建數(shù)據(jù)庫,我們首先需要創(chuàng)建一個空的數(shù)據(jù)庫對象,然后我們才能創(chuàng)建一個新表和定義表的各列。這里有個重要的一點兒就是說,我們創(chuàng)建表的時候,必須在創(chuàng)建完數(shù)據(jù)庫后關(guān)閉數(shù)據(jù)連接。否則我們將沒有辦法創(chuàng)建數(shù)據(jù)庫和定義數(shù)據(jù)列。這就是為什么,我會在接下來創(chuàng)建兩個方法:CreateAccessDB(創(chuàng)建數(shù)據(jù)庫), CreateAccessTB(創(chuàng)建數(shù)據(jù)表),變量DBName用來定義要添加數(shù)據(jù)庫的名字,phyPath用來定義存放數(shù)據(jù)庫文件的路徑。下邊我們來看代碼:

這段代碼包含了一個adovbs.inc文件,這是個非常有用的文件,它定義了ADO和ADOX中用到的所有數(shù)值型變量,你可以在代碼中找到該文件,也可以去你自己電腦上:C:Program FilesCommon FilesSystemado下找到。如果需要在你的頁面中間引用,需要復(fù)制到網(wǎng)站自己的目錄下邊。
下邊是創(chuàng)建數(shù)據(jù)庫的代碼:

數(shù)據(jù)庫創(chuàng)建完了,接下來該表了,否則我們要一個沒有表的數(shù)據(jù)庫是毫無意義的。下邊是創(chuàng)建表的代碼:
1 Sub CreateAccessTB(DBToCreate)
2 Dim catDB ' As ADOX.Catalog
3 Set catDB = Server.CreateObject("ADOX.Catalog")
4 ' Open the catalog
5 catDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
6 "Data Source=" & Server.Mapath(DBToCreate)
7 Dim tblNew ' As ADOX.Table
8 Set tblNew = Server.CreateObject("ADOX.Table")
9 tblNew.Name = TBName
10 ' First Create an Autonumber column, called ID.
11 ' This is just for demonstration purposes.
12 ' You could have done this below with all the other columns as well
13 Dim col ' As ADOX.Column
14 Set col = Server.CreateObject("ADOX.Column")
15 With col
16 ParentCatalog = catDB
17 .Type = adInteger
18 .Name = "ID"
19 .Properties("Autoincrement") = True
20 End With
21 ' Now add the rest of the columns
新聞熱點
疑難解答
圖片精選