How do I create a Microsoft Jet (Access) database without an interop assembly?

﹥>﹥吖頭↗ 提交于 2019-12-03 15:42:18

Before I throw away this code, it might as well live on stackoverflow

Something along these lines seems to do the trick:

if (!File.Exists(DB_FILENAME))
{
    var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME;

    // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. 
    var catType = Type.GetTypeFromProgID("ADOX.Catalog");
    object o = Activator.CreateInstance(catType);
    catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});

    OleDbConnection cnn = new OleDbConnection(cnnStr);
    cnn.Open();
    var cmd = cnn.CreateCommand();
    cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)";
    cmd.ExecuteNonQuery();

}

This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component.

I've done the same as Autsin, create an Access db then included it into my project as a managed resource. Once there, it is included in the compiled code and you can copy it to hard disk as many times as you want. Empty databases are relatively small too, so there isn't much overhead.

The added bonus is the ability to set up the database if you know how it will be used or what tables will be added every time, you can reduce the amount of coding and slow database queries.

You don't need Jet(major headache) installed, if you use this connection string in .net 3.5

Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\myFolder\myAccess2007file.accdb;Persist
Security Info=False;

This should work on access 2007 and below

Interesting question -- I've never thought to create one on the fly like this. I've always included my baseline database as a resource in the project and made a copy when I needed a new one.

Ian

ACE is not in any framework (yet. ie not in 1, 2, 3.5, 4, 4.5)

It's also not part of Windows Update.

JET4 is in Framework2 and above.

If you're working with Access/MDB files etc then do not assume ACE is present.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!