I am using Pyodbc to connect my program with MS Access. In the Access database, I pre-created some queries that require parameters. How can I pass values to parameters of the queries when executing them in Python?
Asked
Active
Viewed 1,585 times
2 Answers
1
When an Access database contains saved parameter queries they are exposed by Access ODBC as stored procedures and can be invoked using the ODBC {call ...}
syntax. For example, with a saved query named [ClientEmails] ...
PARAMETERS prmLastName Text ( 255 );
SELECT Clients.ID, Clients.LastName, Clients.FirstName, Clients.Email
FROM Clients
WHERE (((Clients.LastName)=[prmLastName]));
... the following Python code will run that query and return results for a specific Last Name:
cmd = "{call ClientEmails(?)}"
params = ("Thompson",)
crsr.execute(cmd, params) # pyodbc "cursor" object
for row in crsr.fetchall():
print(row)

Gord Thompson
- 116,920
- 32
- 215
- 418
-1
Here's a generalized example. First, connect to the database. Then, issue commands. The command is just a string. You can incorporate variables from elsewhere in your code through simple string concatenation.
import pyodbc
connStr = """
DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
DBQ=C:\full\path\to\your\PYODBC.accdb;
"""
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
desired_column = "Forename"
table_name = "Student"
command = "SELECT " + desired_column + " FROM " + table_name
cursor.execute(command)
row = cursor.fetchone()
if row:
print(row)

rvictordelta
- 630
- 2
- 8
- 23