简体   繁体   English

合并来自两个不同数据库的表 - sqlite3 / Python

[英]Merge tables from two different databases - sqlite3/Python

I have two different SQLite databases XXX and YYY. 我有两个不同的SQLite数据库XXX和YYY。 XXX contains table A and YYY contains B respectively. XXX包含表A,YYY分别包含B. A and B have same structure(columns). A和B具有相同的结构(列)。 How to append the rows of B in A in Python - SQLite API. 如何在Python中附加A的行 - SQLite API。 After appending A contains rows of A and rows of B. 附加A后包含A行和B行。

You first get a connection to the database using sqlite3.connect , then create a cursor so you can execute sql. 首先使用sqlite3.connect获取与数据库的连接,然后创建游标以便执行sql。 Once you have a cursor, you can execute arbitrary sql commands. 有了游标后,就可以执行任意的sql命令了。

Example: 例:

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. 警告:我实际上没有测试过这个,所以它可能有一些错误,但我认为基本的想法是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM