如何以编程方式在C#中创建Microsoft Access数据库?

如果它不存在,如何在C#中创建Microsoft Access数据库文件?

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

正确的答案是将COM Interop与ADOX库一起使用:

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

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

尝试:

 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

在我的电脑上,Windows 7 sp1 Professional 64位,我找到了Microsoft ADO Ext。 2.8用于C:\ Program Files \ Common Files \ System \ ado \ msadox28.dll中的 DDL和安全

它也被作为参考:

在此处输入图像描述

在参考文献中包含ADOX

在此处输入图像描述

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

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

我找到了这个数据类型列表来创建和读取访问数据库字段

Access Text = adVarWChar

访问备忘录= adLongVarWChar

Access Numeric Byte = adUnsignedTinyInt

Access Numeric Integer = adSmallInt

Access Numeric Long Integer = adInteger

Access Numeric Single Precision = adSingle

Access Numeric Double Precision = adDouble

Access Numeric Replicatie-id = adGuid

Access Numeric Decimal = adNumeric

访问日期/时间= adDate

访问货币= adCurrency

访问AutoNumber = adInteger

访问是/否= adBoolean

访问HyperLink = adLongVarWChar