问题
I'm using pyodbc to get data from a SQL Server, using the script shown here:
conn = pyodbc.connect('DSN=DATASOURCE')
tbl = "SELECT TableA.Field_1 \
FROM TableA \
WHERE TableA.Date>=2019/04/01"
SQL_Query = pd.read_sql_query(tbl, conn)
conn.close
Now I want to make this query into a Python function, where I can change the date (2019/04/01) in the example above as a function variable.
I found pyodbc offers parameterization, but all in the context of cursor.execute
function.
Ideally, I'd like to create a function like this:
def DB_Query(date):
conn = pyodbc.connect('DSN=DATASOURCE')
tbl = "SELECT TableA.Field_1 \
FROM TableA \
WHERE TableA.Date>=?", date
SQL_Query = pd.read_sql_query(tbl, conn)
conn.close
return SQL_Query
Apparently this doesn't work because tbl
has to be a normal string, but is it possible to use pyodbc's parameterization feature together with pandas' pd.read_sql_query
or pd.read_sql
?
回答1:
You can parameterize read_sql_query
in the same way as cursor.execute
by setting the params
parameter:
https://pandas.pydata.org/docs/reference/api/pandas.read_sql_query.html
Example for SQL Server:
import pandas as pd
sql = '''
select *
from Table
where Column = ?
'''
df = pd.read_sql(sql, params=[query_param])
Example for Oracle:
import pandas as pd
sql = '''
select *
from table
where Column = :query_param
'''
df = pd.read_sql(sql, params={'query_param': 'query_value'})
来源:https://stackoverflow.com/questions/60384058/read-database-into-dataframe-using-pyodbc-with-parameterized-query