简体   繁体   中英

Python and SQLite3 - Importing data into an existing database

I'm trying to create an 'import' and 'export' button in my program - using a slight adaptation of the technique found here . However, I find that the import function will only work if the tables in the database do not already exist. Ideally, I want the function to copy all data into the tables, regardless of whether or not it exists.

For example, say we had "myTable" with only one entry, "myRow1". When we import "myData", which has a table named "myTable", with entries "myRow2" and "myRow3", the result should be that "myTable" will have each of the entries "myRow1", "myRow2", and "myRow3".

Here's my current code:

def exportDB():
        filePath, ok = QFileDialog.getSaveFileName(self, "Export file",
                                                   "./exports", "SQL files (*.sql)")
        # QFileDialog provided by PyQt to allow user to select their own filepath
        if ok:
            with open(filePath, 'w') as file:
                for line in connection.iterdump():
                    file.write('%s\n' % line)

def importDB():
    filePath, ok = QFileDialog.getOpenFileName(self, "Import file",
                                               "./exports", "SQL files (*.sql)")
    if ok:
        with open(filePath, 'r') as file:
            data = file.read()
            cursor.executescript(data)

If you examine the export file you should expect to see a "CREATE TABLE" statement and "INSERT INTO" statements for each table/row in the database. I would expect the importDB to fail on the first conflicting "CREATE TABLE".

The sqlite dump functionality is not intended to sync databases. The python doc on iterdump says " This function provides the same capabilities as the .dump command in the sqlite3 shell. ". The sqlite doc on .dump says it gives you what you need " to reconstruct the database at a later time, or on another machine. "

Since the export file is a plain ol' text file, perhaps you could parse it into a useful sync tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM