当前位置:数据库 > Access >>

使用C#创建Access2010或Access2007 accdb 数据库文件

C# 代码
/*
  * 前提条件,你需要先安装Microsoft Access Database Engine 2010 Redistributable 下载地址:
  * http://www.microsoft.com/downloads/zh-cn/details.aspx?familyid=c06b8369-60dd-4b64-a44b-84b371ede16d&displaylang=zh-cn
  * 需要注意的是:下载的版本跟你的程序编译的.NET版本一致,而不是跟操作系统的版本一致。
  *
  * 需要添加引用 Microsoft ADO Ext. 2.8 for DDL and Security 文件位置:C:\Program Files (x86)\Common Files\System\ado\msadox28.tlb
  * 或者 Microsoft ADO Ext. 6.0 for DDL and Security 文件位置:C:\Program Files (x86)\Common Files\System\ado\msadox.dll
*/

//数据库名称可路径
String accdb = "K:\\xxx.accdb";
if (System.IO.File.Exists(accdb)) System.IO.File.Delete(accdb);
ADOX.Catalog cat = new ADOX.Catalog();
cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + accdb);

ADOX.Table tbl = new ADOX.Table();
tbl.ParentCatalog = cat;
tbl.Name = "Table1";

//增加一个自动增长的字段
ADOX.Column col = new ADOX.Column();
col.ParentCatalog = cat;
col.Type = ADOX.DataTypeEnum.adInteger; // 必须先设置字段类型
col.Name = "id";
col.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
col.Properties["AutoIncrement"].Value = true;
tbl.Columns.Append(col, ADOX.DataTypeEnum.adInteger, 0);

//增加一个文本字段
ADOX.Column col2 = new ADOX.Column();
col2.ParentCatalog = cat;
col2.Name = "Description";
col2.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
tbl.Columns.Append(col2, ADOX.DataTypeEnum.adVarChar, 25);

//增加数字字段
ADOX.Column col3 = new ADOX.Column();
col3.ParentCatalog = cat;
col3.Name = "数字";
col3.Type = DataTypeEnum.adDouble;
col3.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
tbl.Columns.Append(col3, ADOX.DataTypeEnum.adDouble, 666);

//增加Ole字段
ADOX.Column col4 = new ADOX.Column();
col4.ParentCatalog = cat;
col4.Name = "Ole类型";
col4.Type = DataTypeEnum.adLongVarBinary;
col4.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
tbl.Columns.Append(col4, ADOX.DataTypeEnum.adLongVarBinary, 0);
//设置主键
tbl.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "id", "", "");
cat.Tables.Append(tbl);

System.Runtime.InteropServices.Marshal.ReleaseComObject(tbl);
System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
tbl = null;
cat = null;
GC.WaitForPendingFinalizers();
GC.Collect();
MessageBox.Show("创建完成!");


作者:孟宪会
补充:软件开发 , C# ,
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,