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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1388971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:56:36  来源:igfitidea点击:

How to create an Access database at runtime in C#?

c#databasems-access

提问by Amit Dhall

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

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

回答by John Feminella

This articlefrom John Russell Plant explains how you'd do it in specific detail with code samples. There are three steps:

这篇来自 John Russell Plant 的文章详细解释了如何使用代码示例进行操作。共有三个步骤:

  1. Create the catalog.
  2. Create the tables.
  3. Release the relevant COM objects.
  1. 创建目录。
  2. 创建表。
  3. 释放相关的 COM 对象。

回答by MRG

Create a blank access database and store it in your resource files.

创建一个空白的访问数据库并将其存储在您的资源文件中。

Now whenever you want to use it, fetch that database from your resources and copy it to wherever you want, rename it to whatever you want and execute your database setup script to create default tables and load values in them.

现在,无论何时您想使用它,从您的资源中获取该数据库并将其复制到您想要的任何位置,将其重命名为您想要的任何名称并执行您的数据库设置脚本以创建默认表并在其中加载值。

回答by Sauron

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.

您需要做的第一件事是获取对 Microsoft ADO Ext 的 COM 引用。XX 表示 DDL 和安全性。XX 代表您的机器上碰巧拥有的任何版本。我的曾经是 2.7 版,但是在 Visual Studio 2008 中,它更新到了 6.0。

alt text http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/AddReference_2.png

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

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

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

alt text http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/Using_2.png

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

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。

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);

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.

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

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);

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

这就对了。您现在应该有一个可以写入的 Access 数据库。希望这可以帮助。

Reference: John Russell Plant - Create an Access Database in C#

参考:John Russell Plant - 在 C# 中创建 Access 数据库

回答by Zamir

Try:

尝试:

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

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

回答by DareDevil

static void IF_EXISTS_DELETE_AND_CREATE(string cn)
{
    //cn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =";
    //cn += AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.mdb"; 
    try
    {
        OleDbConnection connection = new OleDbConnection(cn);
        object[] objArrRestrict;
        objArrRestrict = new object[] { null, null, null, "TABLE" };
        connection.Open();
        DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, objArrRestrict);
        connection.Close();
        string[] list;
        if(schemaTable.Rows.Count > 0)
        {
            list = new string[schemaTable.Rows.Count];
            int i = 0;
            foreach (DataRow row in schemaTable.Rows)
            {
                list[i++] = row["TABLE_NAME"].ToString();
            }
            for ( i = 0; i < list.Length; i++)
            {
                if(list[i] == "TEMP")
                {
                    string deletedl = "DROP TABLE TEMP";
                    using (OleDbConnection conn = new OleDbConnection(cn))
                    {
                        using (OleDbCommand cmd = new OleDbCommand(deletedl, conn))
                        {

                            conn.Open();
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                    break;
                }
            }
        }
        string ddl = "CREATE TABLE TEMP (USERID INTEGER NOT NULL,[ADATE] TEXT(20), [ATIME] TEXT(20))";
        using(OleDbConnection conn = new OleDbConnection(cn))
        {                    
            using(OleDbCommand cmd = new OleDbCommand(ddl, conn))
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    catch (System.Exception e)
    {
        string ex = e.Message;
    }
}