Copy selected columns from SQLite db to another

Step 1: Copy Selected Columns from SQLite Database to Another copy selected columns from SQLite db to another

import sqlite3

# Connect to SQLite database (or create if it doesn't exist)
conn = sqlite3.connect('/Users/kingyhrash/Desktop/db/jo-corpus/jccold/24/Literature-24.sqlite')
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Literature (
	ID INTEGER PRIMARY KEY AUTOINCREMENT,
	Category TEXT,
	Title TEXT,
	Text TEXT,
	Date TEXT,
	URL TEXT,
    Source_table TEXT
);
''')

# Commit the changes and close the connection
conn.commit()
conn.close()   

Step2 # Copy Tables from Source to Destination

import sqlite3


# Connect to the source database
source_conn = sqlite3.connect('path to db/db name.sqlite')
source_cursor = source_conn.cursor()


# Connect to the destination database
destination_conn = sqlite3.connect('path to destination db/Literature-24.sqlite')
destination_cursor = destination_conn.cursor()

try:
    source_cursor.execute('SELECT Category, title, Text, date, Source FROM Written_Filter;')
    data_to_insert = source_cursor.fetchall()

    # Insert data into the destination table 
    for row in data_to_insert:
        destination_cursor.execute("INSERT INTO Literature (Category, Title, Text, Date, URL, Source_table) VALUES (?, ?, ?, ?, ?)", row)

    # Commit the changes in the destination database
    destination_conn.commit()

except sqlite3.Error as e:
    print("SQLite error:", e)

finally:
    # Close connections in a finally block to ensure they are closed even if an exception occurs
    source_conn.close()
    destination_conn.close()

print("Done")


Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Rits Blog by Crimson Themes.