如何使用C#在运行时创建Access数据库? [英] How to create an Access database at runtime in C#?

查看:184
本文介绍了如何使用C#在运行时创建Access数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时使用C#创建Access数据库?

How can I create an Access Database at runtime in C#?

推荐答案

您需要做的第一件事是获取对Microsoft ADO Ext的COM引用. X.X,用于DDL和安全性. X.X代表您的计算机上可能具有的任何版本.我的曾经是2.7版,但是在Visual Studio 2008中,它已更新为6.0版.

The first thing you need to do is get a COM reference to the Microsoft ADO Ext. X.X for DDL and Security. The X.X represents whatever version you happen to have on your machine. Mine used to be version 2.7, but with Visual Studio 2008, it was updated to 6.0.

替代文字http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/AddReference_2.png

添加引用后,ADOX将添加到代码的using部分.

Once you have added the reference, ADOX will be added to the using section of your code.

替代文字http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/Using_2.png

接下来,您将要创建数据库的目录.将所需的文件名插入以下字符串,然后将其传递给CatalogClass.

Next you will want to create the catalog for the database. Insert the filename you wish into the following string and pass it to the CatalogClass.

CatalogClass cat = new CatalogClass();  
string tmpStr;  
string filename = "Sample.MDB";   
tmpStr = "Provider=Microsoft.Jet.OLEDB.4.0;";   
tmpStr += "Data Source=" + filename + ";Jet OLEDB:Engine Type=5";  
cat.Create(tmpStr);

下一步是为数据库创建表和列.如下例所示,这是一个非常简单的操作.

The next step is to create the table and columns for your database. This is a pretty straight forward operation as shown in the example below.

 Table nTable = new Table(); 
 nTable.Name = "PersonData"; 
 nTable.Columns.Append("LastName", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("FirstName", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("Address 1", DataTypeEnum.adVarWChar, 45);
 nTable.Columns.Append("Address 2", DataTypeEnum.adVarWChar, 45); 
 nTable.Columns.Append("City", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("State", DataTypeEnum.adVarWChar, 2);
 nTable.Columns.Append("Zip", DataTypeEnum.adVarWChar, 9);
 cat.Tables.Append(nTable);

最后一步非常重要,否则关闭应用程序时会出错.添加完所有表和列后,您将需要按正确的顺序正确释放com对象.

The final step is very important or you will get error when you close your application. Once the all the tables and columns have been added, you will need to release the com objects properly and in the proper order.

System.Runtime.InteropServices.Marshal.FinalReleaseComObject(nTable); 
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.Tables);    
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection); 
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);

就是这样.现在,您应该具有可以写入的Access数据库.希望这会有所帮助.

That is it. You should now have a Access Database that you can write to. Hope this helps.

参考:约翰·罗素工厂-创建访问数据库在C#

这篇关于如何使用C#在运行时创建Access数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆