2011-01-17 18 views
10

मैं एक डेटाबेस फ़ाइल आयात करने के लिए एक स्क्रिप्ट लिखने के लिए कोशिश कर रहा हूँ। मैंने फ़ाइल को निर्यात करने के लिए स्क्रिप्ट लिखी:अजगर और sqlite3 - आयात और निर्यात डेटाबेस

import sqlite3 

con = sqlite3.connect('../sqlite.db') 
with open('../dump.sql', 'w') as f: 
    for line in con.iterdump(): 
     f.write('%s\n' % line) 

अब मैं उस डेटाबेस को आयात करने में सक्षम होना चाहता हूं। मैंने कोशिश की है:

import sqlite3 

con = sqlite3.connect('../sqlite.db') 
f = open('../dump.sql','r') 
str = f.read() 
con.execute(str) 

लेकिन मुझे एक से अधिक कथन निष्पादित करने की अनुमति नहीं है। एसक्यूएल स्क्रिप्ट को चलाने के लिए इसे पाने का कोई तरीका है?

उत्तर

14
sql = f.read() # watch out for built-in `str` 
cur.executescript(sql) 

Documentation

+0

यह था बनाने के लिए, धन्यवाद – JPC

+0

@adam प्रयास करें - मुझे लगता है कि आप पहली बार एक कर्सर बनाने के लिए मतलब यदि आपने इसे दस्तावेज़ीकरण से कॉपी किया है ("cur।") – RichardTheKiwi

+0

sqlite3 मॉड्यूल या तो उपयोग की अनुमति देता है; अपना चयन ले लो। – bernie

3

का उपयोग कर

con.executescript(str) 

प्रलेखन

Connection.executescript(sql_script) 
    This is a nonstandard shortcut that creates an intermediate cursor object 
    by calling the cursor method, then calls the cursor’s executescript 
    method with the parameters given. 

या कर्सर पहले

import sqlite3 

con = sqlite3.connect('../sqlite.db') 
f = open('../dump.sql','r') 
str = f.read() 
cur = con.cursor() 
cur.execute(str) 
संबंधित मुद्दे