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

LEM*_*ANE 17 .net c# database ms-access winforms

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

SLa*_*aks 17

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

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

var cat = new ADOX.Catalog()
cat.Create(connectionString);
Run Code Online (Sandbox Code Playgroud)

记得使用生成连接字符串OleDbConnectionStringBuilder.

  • 提示:"ADOX库"可以在我的机器上找到"Microsoft ADO Ext.6.0 for DDL and Security" (5认同)

小智 14

尝试:

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;
} 
Run Code Online (Sandbox Code Playgroud)

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


Jim*_*man 10

在我的电脑上,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 
Run Code Online (Sandbox Code Playgroud)

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

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