我在Windows XP上使用python 2.7和内置的sqlite3模块。代码如下所示:#!/usr/bin/env python2
import sqlite3
import sys
def open_db(nam):
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)
当我用db_copy.py src.db dest.db运行这个函数时,源数据库翻了一番。所以我将源文件属性设置为只读。我现在得到:sqlite3.OperationalError: attempt to write a readonly database
似乎在某个地方源和目标数据库连接是混合的?我已经调试了好几个小时没有找到原因。