the_prole
the_prole

Reputation: 8945

How do I import tables from another database in sqlite using Python?

How do I import data from a column in another table in another database into the current database's table's column?

I tried using the "ATTACH" command, but I'm only allowed to execute one statement at a time.

 cursor.execute(
        "ATTACH DATABASE other.db AS other;\
        INSERT INTO table \
        (column1) \
        SELECT column1\
        FROM other.table;")

Upvotes: 1

Views: 2259

Answers (2)

the_prole
the_prole

Reputation: 8945

I had to call execute twice, and enclose other.db is single quotations

 cursor.execute("ATTACH DATABASE 'other.db' AS other;")
 cursor.execute("\
        INSERT INTO table \
        (ID) \
        SELECT ID \
        FROM other.table ;")

Upvotes: 2

Verma
Verma

Reputation: 966

In place of execute you may want to do an executescript. Like so...

cursor.executescript("""ATTACH DATABASE 'other.db' AS other;
                        INSERT INTO table (column1)
                        SELECT column1
                        FROM other.table;""")

(assuming other.db is an sqlite file)

Upvotes: 1

Related Questions