2017-10-11 148 views
0

这是一个简单的问题,我一直无法找到答案。我有一个带有两个命令的.SQL文件。我想让Pandas将这些命令的结果放入DataFrame中。将外部SQL文件读入熊猫数据框

SQL文件的命令就像这样,使用当前日期的较长查询。

SET @todaydate = DATE(NOW()); 
SELECT ...long query....; 

我已经尝试使用read_sql建立我的连接(prod_db)之后通过以下方式和收到错误信息“” NoneType“对象不是可迭代”

sqlpath = 'path.sql' 
scriptFile = open(sqlpath,'r') 
script = scriptFile.read() 
df = pd.read_sql(script,prod_db) 

我也试图使用这里描述reading external sql script in python函数和方法,但我不知道如何获得结果到一个熊猫数据框(或者我错过了一些东西)。它似乎没有读取结果,因为我反复收到“命令跳过”。

def executeScriptsFromFile(filename): 
    fd = open(filename, 'r') 
    sqlFile = fd.read() 
    fd.close() 
    # all SQL commands (split on ';') 
    sqlCommands = sqlFile.split(';') 
    # Execute every command from the input file 
    for command in sqlCommands: 
     try: 
      c.execute(command) 
     except OperationalError, msg: 
      print "Command skipped: ", msg 
df = executescriptsfromfile(sqlpath) 

回答

2

我有一个可能适合您的解决方案。它应该给你一个不错的小pandas.DataFrame

首先,您必须阅读sql文件中的查询。然后,只需使用的pd.read_sql_query()代替pd.read_sql()

我相信你知道它,但这里是该函数的文档:http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_query.html#pandas.read_sql_query

# Read the sql file 
query = open('filename.sql', 'r') 

# connection == the connection to your database, in your case prob_db 
DF = pd.read_sql_query(query.read(),connection) 

我可以向你保证,它正在与T-SQL,但是我从来没有用过MySQL。