简体   繁体   English

使用python循环调用多个SQL数据库

[英]Using python looping to call multiple SQL databases

I want to call multiple databases in Microsoft SQL:我想调用微软SQL中的多个数据库:

driver = 'SQL Server'
server = '123'
tcon = 'yes'
uname = 'name'
pword = 'password'
query = "query1"

I make my databases into list as below:我将我的数据库列在下面的列表中:

db = ['DBA','DBB','DBC']

Then execute looping to call all databases in the list above as below:然后执行循环调用上面列表中的所有数据库,如下所示:

for i in db:
  sql_conn = pyodbc.connect(driver='{SQL Server}', host=server, database= f'{i}',
                  trusted_connection=tcon, user=uname, password=pword)

  df = pd.read_sql(query, sql_conn)

  df['DB_NAME'] = f'{i}' #to add name column in the dataframe

However, i only get data from 'DBC'.但是,我只从“DBC”获取数据。 I want three separate dataframes such as df_DBA, df_DBB, df_DBC from the looping above.我想要三个单独的数据帧,例如 df_DBA、df_DBB、df_DBC 来自上面的循环。

In each loop, df is overwriten with a new dataframe.在每个循环中, df被新的 dataframe 覆盖。 So it will hold data from the last iteration of the loop, which is from DBC since it is the last in the list.因此它将保存来自循环最后一次迭代的数据,该数据来自DBC ,因为它是列表中的最后一个。

If you want separate variables for data from each database, try this:如果您想为每个数据库中的数据提供单独的变量,请尝试以下操作:

def read_sql(query, db_name):
    conn = pyodbc.connect(driver='{SQL Server}', host=server, database=db_name,
                          trusted_connection=tcon, user=uname, password=pword)
    df = pd.read_sql(query, conn)
    df['DB_NAME'] = db_name
    return df


db_DBA = read_sql(query, 'DBA')
db_DBB = read_sql(query, 'DBB')
db_DBC = read_sql(query, 'DBC')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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