問題描述
我有兩個不同的 SQLite 數據庫 XXX 和 YYY.XXX 包含表 A 和 YYY 分別包含表 B.A 和 B 具有相同的結構(列).如何在 Python - SQLite API 中附加 A 中的 B 行.追加 A 后包含 A 行和 B 行.
I have two different SQLite databases XXX and YYY. XXX contains table A and YYY contains B respectively. A and B have same structure(columns). How to append the rows of B in A in Python - SQLite API. After appending A contains rows of A and rows of B.
推薦答案
您首先使用 sqlite3.connect
獲得到數據庫的連接,然后創建一個游標,以便您可以執行 sql.有了游標,就可以執行任意的sql命令了.
You first get a connection to the database using sqlite3.connect
, then create a cursor so you can execute sql. Once you have a cursor, you can execute arbitrary sql commands.
示例:
import sqlite3
# Get connections to the databases
db_a = sqlite3.connect('database_a.db')
db_b = sqlite3.connect('database_b.db')
# Get the contents of a table
b_cursor = db_b.cursor()
b_cursor.execute('SELECT * FROM mytable')
output = b_cursor.fetchall() # Returns the results as a list.
# Insert those contents into another table.
a_cursor = db_a.cursor()
for row in output:
a_cursor.execute('INSERT INTO myothertable VALUES (?, ?, ...etc..., ?, ?)', row)
# Cleanup
db_a.commit()
a_cursor.close()
b_cursor.close()
警告:我還沒有真正測試過這個,所以它可能有一些錯誤,但我認為基本的想法是合理的.
Caveat: I haven't actually tested this, so it might have a few bugs in it, but the basic idea is sound, I think.
這篇關于合并來自兩個不同數據庫的表 - sqlite3/Python的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!