大家好,Python Pandas 大师们。我正在寻找一种与 Python 并行运行一些 SQL 的方法,返回几个 Pandas 数据帧。我有类似于下面的代码,它针对 MS SQL 服务器数据库连续运行 4 个 SQL 查询。与 IO(网络)时间相比,其中两个查询的执行时间要长得多,因此我认为并行化会使代码运行速度快 2 倍。有没有一种简单的方法可以并行执行查询?
理想情况下,我希望能够读取项目子目录中的所有 *.sql 文件,然后触发查询以并行运行并以易于使用的格式(列表?)返回四个数据帧以供进一步使用操作(索引、连接、聚合)。
提前致谢, 兰德尔
# imports
import ceODBC
import numpy as np
import pandas as pd
import pandas.io.sql as psql
from ConfigParser import ConfigParser
import os
import glob
# db connection string
cnxn = 'DRIVER={SQL Server Native Client 11.0}; SERVER=<servername>; DATABASE=<dname>; Trusted_Connection=Yes'
# directories (also should be moved to config)
dataDir = os.getcwd() + '\\data\\'
sqlDir = os.getcwd() + '\\sql\\'
# read sql from external .sql files. Possible to read all *.sql files in a sql dir into a list (or other structure...)?
with open(sqlDir + 'q1.sql', 'r') as f: q1sql = f.read()
with open(sqlDir + 'q2.sql', 'r') as f: q2sql = f.read()
with open(sqlDir + 'q3.sql', 'r') as f: q3sql = f.read()
with open(sqlDir + 'q4.sql', 'r') as f: q4sql = f.read()
# Connect to db, run SQL, assign result into dataframe, close connection.
cnxn = ceODBC.connect(cnxn)
cursor = cnxn.cursor()
# execute the queries and close the connection. Parallelize?
df1 = psql.frame_query(q1sql, cnxn)
df2 = psql.frame_query(q2sql, cnxn)
df3 = psql.frame_query(q3sql, cnxn)
df4 = psql.frame_query(q4sql, cnxn)
# close connection
cnxn.close()