在sqlite3中将表从内存数据库复制到磁盘数据库

ne5o7dgx  于 2023-01-31  发布在  SQLite
关注(0)|答案(1)|浏览(336)

我想使用Python(3.9)从内存中的sqlite数据库复制一个特定的表,在文档中查找,我应该可以简单地使用attach the in-memory database to the file database,但是当我尝试复制表时,它会导致以下错误:
追溯(最近调用最后调用):文件"[在此插入python文件URL]",第21行,文件游标. execute(f'CREATE TABLE "{表名}" AS SELECT * FROM db."{表名}";')sqlite3.操作错误:无此类表格:数据库.表名称
所以,即使它很好地附加了数据库(或者至少是一个内存数据库),它似乎也找不到数据库中的表。
测试代码:

import sqlite3

#memory database
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
#file database
file_conn= sqlite3.connect(r"C:\...\testfile.sqlite") #insert your own URL here
file_cursor = file_conn.cursor()

table_name = "table_name"
#Create table in memory db
cursor.execute(f"CREATE TABLE {table_name} (id INTEGER, Value INTEGER, Value2 INTEGER, Category INTEGER);")
conn.commit()
cursor.execute(f"INSERT INTO {table_name} (id, Value, Value2, Category) "
               f"VALUES ('1', '20','20', '2'),"
               f"('2', '30','30', '2'),"
               f"('13', '17','17','1');")
conn.commit()
# copy table to file db
file_cursor.execute(f"ATTACH DATABASE ':memory:' AS db;")
file_conn.commit()
file_cursor.execute(f"CREATE TABLE '{table_name}' AS SELECT * FROM db.'{table_name}';")
file_conn.commit()
file_conn.close()
conn.close()
ztmd8pv5

ztmd8pv51#

您不需要单独连接到文件数据库。
使用内存中数据库的连接来 * 附加 * 文件数据库:

import sqlite3

#connection to memory db
conn = sqlite3.connect(":memory:")

cursor = conn.cursor()

table_name = "table_name"

#Create table in memory db
cursor.execute(f"CREATE TABLE [{table_name}] (id INTEGER, Value INTEGER, Value2 INTEGER, Category INTEGER);")
cursor.execute(f"INSERT INTO [{table_name}] (id, Value, Value2, Category) "
               f"VALUES ('1', '20','20', '2'),"
               f"('2', '30','30', '2'),"
               f"('13', '17','17','1');")
conn.commit()

# copy table to file db
cursor.execute(r"ATTACH DATABASE 'C:\...\testfile.sqlite' AS db;")
cursor.execute(f"CREATE TABLE db.[{table_name}] AS SELECT * FROM [{table_name}];")
conn.commit()
conn.close()

相关问题