MapMan
MapMan

Reputation: 668

How do I create a .MDB and import a CSV into it using Python

Does anyone have any examples of creating a new Access Database and importing a CSV file (only specific fields) into the database?

Thanks

Upvotes: 2

Views: 2509

Answers (2)

pypyodbc
pypyodbc

Reputation: 1139

You can use PyPyODBC to do this.

To create an Access mdb file:

import pypyodbc
pypyodbc.win_create_mdb( "D:\\Your MDB file path.mdb" )

If you want, you can continue to use pypyodbc to connect to the creatmdb files and manipulate them with ODBC interface similar to pyodbc:

conn = pypyodbc.connect(u'''Driver={Microsoft Access Driver (*.mdb)};DBQ='''+mdb_path
                    , unicode_results = True
                    , readonly = False)

cur = conn.cursor()
cur.execute ('Drop table pypyodbc_test_tabl')
cur.execdirect(u"""create table pypyodbc_test_tabl (ID integer PRIMARY KEY,product_name text)""")

...
cur.close()
conn.commit()
conn.close()

Finally, To compact an existing Access mdb file

pypyodbc.win_compact_mdb("D:\\The path to the original to be compacted mdb file"
                   ,"D:\\The path to put the compacted new mdb file")

Upvotes: 1

MWR
MWR

Reputation: 170

Here is an idea and a link for further info:

I have not tested the following for creating a new mdb so ymmv!

import win32com.client
eng=win32com.client.gencache.EnsureDispatch("DAO.DBEngine.36")
eng.CreateDatabase("c:\\myNewAccessdB.mdb", win32com.client.constants.dbLangGeneral)

Here is a link to some good info for working with python and ado.

I hope this helps.

~M

Sorry I do not have any examples for working the csv into the empty mdb :( If I come with anything I will post later.

Upvotes: 2

Related Questions