2017-03-03 79 views
0

我有下面的代碼將我的SQL查詢的所有結果放到預定義的HTML和文本文檔中。我想根據它正在處理的數據庫中的messages.conversation_id column將它們寫入單獨的文件中。我可以使用哪種功能來做到這一點?我在我所做的研究中找不到任何東西。編寫SQLite數據庫查詢來分離文件

預先感謝您。

cur = cur.execute("""SELECT DISTINCT messages.conversation_id 
       FROM messages 
       INNER JOIN participants_info ON messages.participant_id = participants_info._id 
       WHERE messages.conversation_id IS NOT NULL;""") 

query = ("""SELECT strftime('%Y-%m-%d %H:%M:%S',messages.date/1000,'unixepoch'), participants_info.number, participants_info.contact_name, messages.body, messages.conversation_id, messages.participant_id 
     FROM messages 
     INNER JOIN 
     participants ON messages.participant_id = participants._id 
     INNER JOIN 
     participants_info ON participants.participant_info_id = participants_info._id 
     WHERE messages.conversation_id = ? 
     ORDER BY messages.date;""") 


with open('messages.html', 'w') as h, open('test.txt', 'w') as t: 
for convo in cur.fetchall(): 
    df = pd.read_sql_query(query, conn, params=convo) 

    # HTML WRITE 
    h.write(df.to_html()) 
    h.write('<br/>') 

    # TXT WRITE 
    t.write(df.to_string()) 
    t.write('\n\n') 
+1

交換與和報表您的訂單,並與適應的open()有一個動態的文件名,而不是一個靜態的名字 – Boud

+0

我怎麼會指定SQL查詢作爲一個動態的變量?對不起,第一次使用SQLite和Python! – Nathan1995

+0

當然,不用擔心,評論在這裏也是爲了回答靈感,而有人真的這樣做。查看Nathan的答案。 – Boud

回答

0
cur = cur.execute("""SELECT DISTINCT messages.conversation_id 
      FROM messages 
      INNER JOIN participants_info ON messages.participant_id = participants_info._id 
      WHERE messages.conversation_id IS NOT NULL;""") 

query = ("""SELECT strftime('%Y-%m-%d %H:%M:%S',messages.date/1000,'unixepoch'), participants_info.number, participants_info.contact_name, messages.body, messages.conversation_id, messages.participant_id 
    FROM messages 
    INNER JOIN 
    participants ON messages.participant_id = participants._id 
    INNER JOIN 
    participants_info ON participants.participant_info_id = participants_info._id 
    WHERE messages.conversation_id = ? 
    ORDER BY messages.date;""") 


for convo in cur.fetchall(): 
    with open('{}.html'.format(convo), 'w') as h, open('{}.txt'.format(convo), 'w') as t: 
    df = pd.read_sql_query(query, conn, params=convo) 

# HTML WRITE 
h.write(df.to_html()) 
h.write('<br/>') 

# TXT WRITE 
t.write(df.to_string()) 
t.write('\n\n')