How to create Microsoft Access database in C# programmatically?

后端 未结 4 2094
傲寒
傲寒 2020-12-01 08:23

How do you create a Microsoft Access database file in C# if it does not exist yet?

4条回答
  •  遥遥无期
    2020-12-01 08:43

    You can use the CreateDatabase method in the DAO / ACE library (it's installed with Office, or available for download from here).

    // using Microsoft.Office.Interop.Access.Dao;
    // using static Microsoft.Office.Interop.Access.Dao.DatabaseTypeEnum;
    
    const string dbLangGeneral = ";LANGID=0x0409;CP=1252;COUNTRY=0";
    
    var engine = new DBEngine();
    var dbs = engine.CreateDatabase(@"c:\path\to\database.accdb", dbLangGeneral, dbVersion120);
    dbs.Close();
    dbs = null;
    

    Note that depending on the version of Access/Jet you want your database to support, you can use other values from the DatabaseTypeEnum enum:

    • dbVersion10
    • dbVersion11
    • dbVersion20
    • dbVersion30
    • dbVersion40
    • dbVersion120
    • dbVersion140
    • dbVersion150

    Also note that you can choose to encrypt the database, or select a different collation.

    NB: If you have a 64-bit machine, and want to run the code as part of a 64-bit program, you'll need the 64-bit version of the engine. If you already have the 32-bit version installed (either via Office, or via the download), you'll have to run the 64-bit installer with the /passive and /silent flags; otherwise you'll get a message that you can't install 64-bit components over previously installed 32-bit components.

提交回复
热议问题