2017-03-03 9 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

スワップあなたとのとのための文の順序、および(オープンで適応)私は、動的変数としてSQLクエリを割り当てますどのように静的な名前 – Boud

+0

動的なファイル名を持っていないするには?ごめんなさいSQLiteとPythonで初めて作業しています! – Nathan1995

+0

確かに、心配はありません、コメントはまたインスピレーションの回答のためにここにいた、そして誰かが実際にそれをしました。ネイサンの答えをチェックしてください。 – 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') 
関連する問題