我有下面的代码,它将我的SQL查询的所有结果放入预定义的HTML和文本文档中。我想根据它所使用的数据库中的messages.conversation_id column
将它们写入单独的文件中。我可以使用哪个功能来执行此操作?我在研究中找不到任何东西。
提前谢谢。
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')
答案 0 :(得分: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')