2011-01-24 83 views
14

如何在C#中创建Microsoft Access数据库文件(如果它不存在)?如何以编程方式在C#中创建Microsoft Access数据库?

+0

是否有要访问或者是你寻找一个文件基于数据库的解决方案存储数据如果这就是你所需要的,SQLite是很好的和可移植的。 – jlafay 2011-01-25 19:04:13

+0

是的,我现在在Android上使用SQLite。 – 2014-10-23 04:31:54

回答

15

最简单的答案是在您的程序中嵌入一个空的.mdb/.accdb文件并将其写入磁盘。

正确的答案是使用COM互操作与ADOX库:

var cat = new ADOX.Catalog() 
cat.Create(connectionString); 

记住使用OleDbConnectionStringBuilder生成您的连接字符串。

+3

提示:在我的机器 – Matthias 2016-05-15 21:23:29

9

尝试:

using ADOX; //Requires Microsoft ADO Ext. 2.8 for DDL and Security 
using ADODB; 

public bool CreateNewAccessDatabase(string fileName) 
{ 
bool result = false; 

ADOX.Catalog cat = new ADOX.Catalog(); 
ADOX.Table table = new ADOX.Table(); 

//Create the table and it's fields. 
table.Name = "Table1"; 
table.Columns.Append("Field1"); 
table.Columns.Append("Field2"); 

try 
{ 
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5"); 
    cat.Tables.Append(table); 

    //Now Close the database 
    ADODB.Connection con = cat.ActiveConnection as ADODB.Connection; 
    if (con != null) 
    con.Close(); 

    result = true; 
} 
catch (Exception ex) 
{ 
    result = false; 
} 
cat = null; 
return result; 
} 

http://zamirsblog.blogspot.com/2010/11/creating-access-database.html

9

在我的电脑中,Windows 7 SP1专业版64位,我发现微软ADO分机。 2.8 for DDL and Security in C:\ Program Files \ Common Files \ System \ ado \ msadox28.dll

还发现作为参考:

其包括作为ADOX在参考文献中

enter image description here

默认情况下,列被创建为文本[ 255]。以下是一些将列创建为不同数据类型的示例。

table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6] 
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger); // Integer 

我发现数据类型来创建列表和读取访问数据库中的字段

访问文本= adVarWChar

访问备注= adLongVarWChar

访问数字字节= adUnsignedTinyInt

访问数字整数= adSmallInt

访问数字长整型= adInteger

访问数字单精度= adSingle

访问数字双精度= adDouble

访问数字Replicatie-ID = adGuid

访问数字小数= adNumeric

访问日期/时间= adDate

访问货币= adCurrency

访问自动编号= adInteger

访问是/否= adBoolean

访问的HyperLink = adLongVarWChar

相关问题