3

I am using the following code to read a table from an access db as a pandas dataframe:

import pyodbc 
import pandas as pd

connStr = (
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\A\Documents\Database3.accdb;"
    )
cnxn = pyodbc.connect(connStr)

sql = "Select * From Table1"
data = pd.read_sql(sql,cnxn)  # without parameters [non-prepared statement]

# with a prepared statement, use list/tuple/dictionary of parameters depending on DB
#data = pd.read_sql(sql=sql, con=cnxn, params=query_params) 

I plan to make some transformations and then write the dataframe back into the databsae in a similar way. Does anyone know how I can do this?.

Thank you

6
  • github.com/gordthompson/sqlalchemy-access Commented Jun 8, 2022 at 20:54
  • Thanks. Would this syntax be correct then?: pandas.pydata.org/docs/reference/api/… Commented Jun 8, 2022 at 21:29
  • I'll try add this also from sqlalchemy import create_engine engine = create_engine("access+pyodbc://@your_dsn") Commented Jun 8, 2022 at 21:31
  • Yes, .to_sql() is what you would use. Commented Jun 8, 2022 at 21:35
  • Thank you so much! problem solved. I would upvote you but I don't have enough scores to do so. Commented Jun 8, 2022 at 21:46

1 Answer 1

2

When working with pandas and a database other than SQLite we need to use SQLAlchemy. In this case, we would use the sqlalchemy-access dialect.

(I am currently the maintainer.)

Example:

import pandas as pd
import sqlalchemy as sa 

connection_string = ( 
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    r"DBQ=C:\Users\Public\test\sqlalchemy-access\sqlalchemy_test.accdb;"
    r"ExtendedAnsiSQL=1;" )
connection_url = sa.engine.URL.create(
    "access+pyodbc",
    query={"odbc_connect": connection_string}
)
engine = sa.create_engine(connection_url)

df = pd.DataFrame([(1, "foo"), (2, "bar")], columns=["id", "txt"])
df.to_sql("my_table", engine, index=False, if_exists="append")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.