问题
value_date = (pd.to_datetime('30-Oct-2019').strftime('%d-%b-%Y')).upper()
iss_cnxn = pyodbc.connect('driver={SQL Server Native Client 11.0};'
'server=abc;'
'database=xyz;'
'trusted_connection=yes')
sql_query = ' '.join(f"""select
xxx as x,
yyy as y,
zzz as z,
from dbo.abcd P WITH(NOLOCK)
where filedate = '{value_date}'""".split())
What is the best way to determine the database based on the ‘filedate’ that we are querying? In the example I have hardcoded the value_date as 30th Oct 2019 but we will pass the date parameter later. Is there any function or something to switch the database based on filedate ? There should be some connection between the filedate and switching the database. Please suggest.
回答1:
You can use a simple if statement to modify the db name and use string formatting to pass the correct db name to your connection. For example if the query_date is in the future, use db1, else use db2. Change datetime.now() to whatever date you want.
from datetime import datetime
if query_date > datetime.now():
db = 'db1'
else:
db = 'db2'
iss_cnxn = pyodbc.connect('driver={SQL Server Native Client 11.0};'
'server=abc;'
'database={};'.format(db)
'trusted_connection=yes')
回答2:
You could pass the data in a create_db function.
def create_db_conn(value_date):
if value_date == 'xyz':
db = 'db1'
else:
db = 'db2'
iss_cnxn = pyodbc.connect('driver={SQL Server Native Client 11.0};'
'server=abc;'
'database={};'.format(db)
'trusted_connection=yes')
return iss_cnxn
This will make your connection dynamic according to value_date. You can write another function to close this connection as well.
来源:https://stackoverflow.com/questions/60434940/python-how-to-switch-from-one-database-to-another-depending-upon-filedate-in-t