官方QQ群:127876820【C#编程技术-全国站--未满人】

详解C#动态创建Access数据库及密码

以前工作中需要全新的Access数据库,可以复制数据库,也可以把新的数据库放到资源里面,用新数据库的时候释放出来,都感觉不爽,还是动态生成心理舒服。

  生成数据库要使用ADO,首先添加引用。

using System.IO;  
using System.Data.OleDb;
//连接Access数据库  
using ADOX;                              
//引用COM:Microsoft ADO Ext. 2.8 for DDL and Security    
//添加引用:Microsoft ActioveX Data Objects 2.8 Library

  创建数据库:

  然后使用ADODB创建数据库,直接看代码:

string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName;  
//创建数据库  
ADOX.Catalog catalog
= new Catalog();  
try    
   {        
    catalog.Create(conn);      
   }      
catch  {}      
//连接数据库    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; // 必须先设置字段类型    
column.Name
= "ID";    
column.DefinedSize
= 9;    
column.Properties[
"AutoIncrement"].Value = true;    
table.Columns.Append(column, DataTypeEnum.adInteger,
0);    //设置主键    
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);    
}    

//此处一定要关闭连接,否则添加数据时候会出错          

table
= null;    
catalog
= null;    
Application.DoEvents();    
cn.Close();
posted @ 2010-10-01 22:32  碧海蓝天_C#  阅读(552)  评论(1编辑  收藏  举报
官方QQ群:127876820【C#编程技术-全国站--未满人】