以前工作中需要全新的Access數(shù)據(jù)庫,可以復(fù)制數(shù)據(jù)庫,也可以把新的數(shù)據(jù)庫放到資源里面,用新數(shù)據(jù)庫的時候釋放出來,都感覺不爽,還是動態(tài)生成心理舒服。生成數(shù)據(jù)庫要使用ADO,首先添加引用。
using System.IO;
using System.Data.OleDb; //連接Access數(shù)據(jù)庫
using ADOX;
//引用COM:Microsoft ADO Ext. 2.8 for DDL and Security
//添加引用:Microsoft ActioveX Data Objects 2.8 Library
創(chuàng)建數(shù)據(jù)庫:然后使用ADODB創(chuàng)建數(shù)據(jù)庫,直接看代碼:
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName;
//創(chuàng)建數(shù)據(jù)庫
ADOX.Catalog catalog = new Catalog();
try
{
catalog.Create(conn);
}
catch
{}
//連接數(shù)據(jù)庫
ADODB.Connection cn = new ADODB.Connection();
cn.Open(conn, null, null, -1);
catalog.ActiveConnection = cn;
//新建表
ADOX.Table table = new ADOX.Table();
table.Name = "AdPlayList";
ADOX.Column column = new ADOX.Column();
column.ParentCatalog = catalog;
column.Type = ADOX.DataTypeEnum.adInteger; // 必須先設(shè)置字段類型
column.Name = "ID";
column.DefinedSize = 9;
column.Properties["AutoIncrement"].Value = true;
table.Columns.Append(column, DataTypeEnum.adInteger, 0);
//設(shè)置主鍵
table.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "ID", "", "");
table.Columns.Append("FileName", DataTypeEnum.adVarWChar, 50);
table.Columns.Append("FileDate", DataTypeEnum.adDate, 0);
table.Columns.Append("FileSize", DataTypeEnum.adInteger, 9);
table.Columns.Append("OrderID", DataTypeEnum.adInteger, 9);
table.Columns.Append("Sha1", DataTypeEnum.adVarWChar, 50);
try
{
catalog.Tables.Append(table);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//此處一定要關(guān)閉連接,否則添加數(shù)據(jù)時候會出錯
table = null;
catalog = null;
Application.DoEvents();
更多信息請查看IT技術(shù)專欄