Copying a table from an in-memory database to a on-disk database in sqlite3

Question:

I want to copy one specific table from an in-memory sqlite database, using Python (3.9). Looking in the documentation, I should be able to simply attach the in-memory database to the file database, however while attaching throws no error, when I try to copy the table over, it results in the following error:

Traceback (most recent call last):
File "[insert python file URL here]", line 21, in
file_cursor.execute(f’CREATE TABLE "{table_name}" AS SELECT * FROM db."{table_name}";’)
sqlite3.OperationalError: no such table: db.table_name

So, even though it is attaching the database just fine (or at least a memory database), it appears not to be able to find the tables within that database. What can I do?

test code:

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()
Asked By: MappingThePast

||

Answers:

You don’t need a separate connection to the file db.
Use the connection of the in-memory db to attach the file db:

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()
Answered By: forpas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.