There are a lot of tips online on how to use pyodbc to run a query in MS Access 2007, but all those queries are coded in the Python script itself. I would like to use pyodbc to call the queries already saved in MS Access. How can I do that?
If the saved query in Access is a simple SELECT query with no parameters then the Access ODBC driver exposes it as a View so all you need to do is use the query name just like it was a table:
import pyodbc
connStr = (
r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=C:\Users\Public\Database1.accdb;"
)
cnxn = pyodbc.connect(connStr)
sql = """\
SELECT * FROM mySavedSelectQueryInAccess
"""
crsr = cnxn.execute(sql)
for row in crsr:
print(row)
crsr.close()
cnxn.close()
If the query is some other type of query (e.g., SELECT with parameters, INSERT, UPDATE, ...) then the Access ODBC driver exposes them as Stored Procedures so you need to use the ODBC {CALL ...} syntax, as in
import pyodbc
connStr = (
r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=C:\Users\Public\Database1.accdb;"
)
cnxn = pyodbc.connect(connStr)
sql = """\
{CALL mySavedUpdateQueryInAccess}
"""
crsr = cnxn.execute(sql)
cnxn.commit()
crsr.close()
cnxn.close()
Related
I'm using 32-bit Python along with 32-bit Microsoft Access.
I connect to the database and create a cursor.
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=P:\path\database.accdb;')
c = conn.cursor()
I then read in a table for future use:
c.execute('select * from tbl')
tbl = c.fetchall()
But when I try to make a copy of the table using:
query = 'CREATE TABLE tbl2 LIKE tbl'
c.execute(query)
I get a programming error:
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement. (-3551) (SQLExecDirectW)')
I'm new to PYODBC but this is a pretty basic SQL line. Any tips on what might be wrong?
Due to a lack of documentation, the best way I found to figure this out is to use Microsoft Access to create a template for the query...example below worked.
query = 'SELECT tbl.* INTO tbl2 FROM tbl'
c.execute(query)
I am now facing a difficulty connecting VIEW table in mdb file using pyodbc.
Current code is as follows:
(Previous Provider: Microsoft.Jet.OLEDB.4.0)
import pyodbc
pyodbc.pooling = False
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:***.mdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
for table_info in crsr.tables(tableType='TABLE'):
print(table_info.table_name)
strSQL = "SELECT A,B FROM tableC WHERE ** ORDER BY B"
crsr.execute(strSQL)
for row in crsr.fetchall():
print(row)
When it works, for table_info in crsr.tables(tableType='TABLE'): seems to have no issue.
This is because print(table_info.table_name) displays several table names.
However, when crsr.execute(strSQL) is done, exeption error has raised and following message
('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] ODBC--connection to 'VIEW' failed. (-2001) (SQLExecDirectW)")
is shown.
It would be appreciated to instruct me how to overcome this issue.
Thanks.
I am operating a python 3 notebook in Azure Data Studio (similar to jupyter notebook) and trying to access an existing global temp table (##TEMP1) via pyodbc.
Here is my code:
import pandas as pd
import pyodbc
con = pyodbc.connect(
Trusted_Connection="yes",
driver="{ODBC Driver 17 for SQL Server}",
host="SERVERNAME",
database=db,
trustServerCertificate="yes",
multisubnetfailover="yes",
applicationIntent="ReadOnly",
)
sql = """
select * from ##TEMP1
"""
data = pd.read_sql(sql, con)
con.close()
data.head()
In Azure Data Studio, when I switch the kernel to sql and simply query select * from ##TEMP1, it returns results, however when I try to run via the python code above via pyodbc, it's returning the following error.
DatabaseError: Execution failed on sql ' select * from ##TEMP1 ':
('####', "[####] [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Invalid object name '##TEMP1'. (###) (SQLExecDirectW)")
Please help, those much smarter than I! :)
I think you want something like this:
I use pyodbc to make the connection and query the database. As you can see I create a curser with pyodbc and execute the curser with the SQL query string as an argument. Then use fetchall() to return the result for the curser
import pandas as pd
import pyodbc
con = pyodbc.connect(Trusted_Connection='yes', driver = '{ODBC Driver 17 for SQL Server}',host = 'SERVERNAME', database = db,trustServerCertificate='yes',multisubnetfailover='yes',applicationIntent='ReadOnly')
crsr = conn.cursor()
sql = '''
select * from ##TEMP1
'''
crsr.execute(sql)
results = crsr.fetchall()
con.close()
data.head()
I am trying to create tables in a MS Access DB with python using pyodbc but when I run my script no tables are created and no errors are given. My code:
#!/usr/bin/env python
import pyodbc
con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDASQL;')
cur = con.cursor()
string = "CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)"
cur.execute(string)
What could be wrong?
You need to commit the transaction:
import pyodbc
con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDASQL;')
cur = con.cursor()
string = "CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)"
cur.execute(string)
con.commit()
Additional solutions that do not require a manual commit are:
Set autocommit = True when the connection instance is created.
Eg:
con = pyodbc.connect(your_connection_string, autocommit = True)
OR
Use a with statement that, according to Python Database connection Close, will commit anything before the connection is deleted at the end of the with block.
Eg:
with pyodbc.connect(your_connection_string) as con:
CREATE_TABLE_CODE_WITHOUT_COMMIT
UNRELATED_CODE
Basically I'm trying to update Column1_mbgl field data in Table1, all based in MS Access database. The script gets executed without any errors, but when the table is checked no update occurred. I have tried two options as shown in the code without any success. The second option is the SQL code generated directly from MS Access query. Can anybody suggest what I'm missing in the code?
#import pypyodbc
import pyodbc
# MS ACCESS DB CONNECTION
pyodbc.lowercase = False
conn = pyodbc.connect(
r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
r"Dbq=C:\temp\DB_access.accdb;")
# OPEN CURSOR AND EXECUTE SQL
cur = conn.cursor()
# Option 1 - no error and no update
cur.execute("UPDATE Table1 SET Column1_mbGL = Column2_mbGL-0.3 WHERE ((Column3_name='PZ01') AND (DateTime Between #6/14/2016 14:0:0# AND #6/16/2016 12:0:0#) AND (TYPE='LOG'))");
# Option 2 - no error and no update
#cur.execute("UPDATE Table1 SET Table1.Column1_mbGL = [Table1]![Column2_mbGL]-0.3 WHERE (((Table1.Column3_name)='PZ01') AND ((Table1.DateTime) Between #6/14/2016 14:0:0# And #6/16/2016 12:0:0#) AND ((Table1.TYPE)='LOG'))");
cur.close()
conn.close()
You forgot to conn.commit() after executing your UPDATE query. The Python database API specifies that connections open with "autocommit" off by default, so an explicit commit is needed.