Search code examples
pythonms-accessinsertwin32com

Write to MS Access table, python win32com


I'm playing around with win32com.client for python to try to write/insert a row to a MS Access table. I've found an example of how to connect and query an Access table here. Basically, their code slightly modified for my own use is:

import win32com.client

connection = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:\\testdb.mdb;'
connection.Open(DSN)
recordset = win32com.client.Dispatch(r'ADODB.Recordset')
recordset.Open('SELECT * FROM Table1', connection, 1, 3)
fields_dict = {}
for x in range(recordset.Fields.Count):
    fields_dict[x] = recordset.Fields.Item(x).Name
    print fields_dict[x], recordset.Fields.Item(x).Value

So this tells me how to execute a select statement on the Access table. I'd like to be able to write rows and data to the table. When using win32com for MS Office products, I tend to dive into the MSDN pages and try to interpret the VBA code for python code, but this one has me a bit handcuffed. Couple that with no examples found on the internet after lengthy searches has made me second guess whether or not this is possible? hopefully someone out there has played with this before and has a suggestion.


Solution

  • As I mentioned in my comment to the question, using pyodbc (or pypyodbc) and the Access ODBC driver is a more common way of doing CRUD operations, but if you really want to use win32com and OLEDB then you could do an UPDATE like this:

    import win32com.client
    
    # ADODB constants
    adVarWChar = 202
    adInteger = 3
    adParamInput = 1
    
    connection = win32com.client.Dispatch(r'ADODB.Connection')
    DSN = (
        r'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
        r'DATA SOURCE=C:\Users\Public\mdbTest.mdb;'
        )
    connection.Open(DSN)
    cmd = win32com.client.Dispatch(r'ADODB.Command')
    cmd.ActiveConnection = connection
    cmd.CommandText = "UPDATE Donors SET LastName = ? WHERE ID = ?"
    cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255))
    cmd.Parameters.Append(cmd.CreateParameter("?", adInteger, adParamInput))
    cmd.Parameters(0).Value = "Thompson"
    cmd.Parameters(1).Value = 10
    cmd.Execute()
    connection.Close()