2013-05-12 10 views
3

Windows XP에서 내장 sqlite3 모듈과 함께 python 2.7을 사용하고 있습니다. 코드는 다음과 같습니다한 데이터베이스에서 다른 데이터베이스로 파이썬 sqlite 복사 테이블

#!/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 이것을 실행하면. 그래서 나는 readonly 소스 파일 속성을 설정합니다. 나는 지금 얻는다 :

sqlite3.OperationalError: attempt to write a readonly database 

어딘가에 근원과 목적지 데이터베이스 연결이 섞여있는 것처럼 보입니까? 원인을 찾지 않고 몇 시간 동안 이것을 디버깅했습니다.

답변

3

당신은 nam 매개 변수를 무시하고 open_db() 모든 통화에 대해 sys.argv[1]을 사용하고 있습니다 :

def open_db(nam): 
    conn = sqlite3.connect(sys.argv[1]) 

src_conndest_conn 모두로, 첫 번째라는 이름의 데이터베이스 두 번을 엽니 다. 대신 nam을 사용하십시오.

def open_db(nam): 
    conn = sqlite3.connect(nam)