SQLite User Forum

Attach file to in-memory database
Login

Attach file to in-memory database

(1) By anonymous on 2022-03-25 15:14:07 [link] [source]

Hello! I tried to attach non-existing file to previosly created in-memory database and write data from in-memory databese to file database by SQL query. The simlest python code to reproduce below.

import sqlite3 print("sqlite version", sqlite3.sqlite_version) con = sqlite3.connect(":memory:") #create in-memory database cur = con.cursor() cur.execute('CREATE TABLE tab (fld TEXT)') #create table in-memory cur.execute('INSERT INTO tab VALUES ("some text")') # and fill it cur.execute('ATTACH DATABASE :file AS store', {"file": "store.db"}) #attach file, which not exists cur.execute('CREATE TABLE "store.tab" (fld TEXT)') # create table in file cur.execute('INSERT INTO "store.tab" SELECT fld FROM tab') # write data from in-memory table cur.execute('SELECT * FROM "store.tab"') # try read data back - OK print(cur.fetchall()) con.commit() con.close()

Output:

sqlite version 3.31.1 [('some text',)]

File "store.db" was created, and last SELECT query show data were written, but nothing was written to file. It just has 0 bytes.

(2) By Keith Medcalf (kmedcalf) on 2022-03-25 17:29:21 in reply to 1 [source]

The table "store.tab" is a table in the main schema. If you want the table name to be tab in the schema store then you would need to use that reference: store.tab or, for lovers of extranous symbol quoting, "store"."tab".

THe results obtained are exactly what you requested.

(3) By anonymous on 2022-03-25 17:38:57 in reply to 2 [link] [source]

Thank you!