5/31/2020 Python sqlite copy table from one database to another - Stack Overflow
Python sqlite copy table from one database to another
Asked 7 years ago Active 7 years ago Viewed 8k times
I'm using python 2.7 with the builtin sqlite3 module on Windows XP. The code looks like the following:
3 #!/usr/bin/env python2
import sqlite3
import sys
def open_db(nam):
5 conn = sqlite3.connect(sys.argv[1])
# Let rows returned be of dict/tuple type
conn.row_factory = sqlite3.Row
print "Openned database %s as %r" % (nam, conn)
return conn
def copy_table(table, src, dest):
print "Copying %s %s => %s" % (table, src, dest)
sc = src.execute('SELECT * FROM %s' % table)
ins = None
dc = dest.cursor()
for row in sc.fetchall():
if not ins:
cols = tuple([k for k in row.keys() if k != 'id'])
ins = 'INSERT OR REPLACE INTO %s %s VALUES (%s)' % (table, cols,
','.join(['?'] * len(cols)))
print 'INSERT stmt = ' + ins
c = [row[c] for c in cols]
dc.execute(ins, c)
dest.commit()
src_conn = open_db(sys.argv[1])
dest_conn = open_db(sys.argv[2])
copy_table('audit', src_conn, dest_conn)
When I run this with db_copy.py src.db dest.db the source database was doubled. So I set the
source file attribute to readonly. I now get:
sqlite3.OperationalError: attempt to write a readonly database
It seems somewhere the source and destination database connections are mixed? I've been
debugging this for hours without finding the cause.
python sqlite pysqlite
asked May 12 '13 at 12:18
Ayman
9,921 13 55 87
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
Terms of Service.
https://stackoverflow.com/questions/16507276/python-sqlite-copy-table-from-one-database-to-another 1/2
5/31/2020 Python sqlite copy table from one database to another - Stack Overflow
Active Oldest Votes
1 Answer
You are ignoring the nam parameter and using sys.argv[1] for all calls to open_db() :
3 def open_db(nam):
conn = sqlite3.connect(sys.argv[1])
This opens the first named database twice, as both src_conn and dest_conn . Use nam instead:
def open_db(nam):
conn = sqlite3.connect(nam)
answered May 12 '13 at 12:22
Martijn Pieters ♦
814k 199 3085
2715
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our
Terms of Service.
https://stackoverflow.com/questions/16507276/python-sqlite-copy-table-from-one-database-to-another 2/2