简体   繁体   中英

Run the query saved in MS Access with required parameters through Pyodbc?

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM