2017-10-11 149 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。