Python : How to switch from one database to another depending upon filedate in the query through 'pyodbc.connect' or something?

混江龙づ霸主 提交于 2021-01-20 12:32:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!