将数据从 sqlite3 转换为 csv 的问题,xml 使用 python3

Issues converting data from sqlite3 to csv, xml using python3

*注意 - 这是一项作业,而不是提供解决方案,如果你能指出我弄乱我的代码的地方,那将不胜感激。

我正在编写一个与 sqlite3 table、XML 文件和 csv 文件交互的小程序。当用户第一次运行程序时,我会检查应用程序目录中的每个文件,然后创建它们/用数据填充它们。

应该发生什么(当目录中没有文件时): 1. 创建一个table (payrate.db) 2. 将值插入 table 3. 使用 table 中的数据,将相同的值插入 XML 文件 (payrate.xml) 4. 同样,使用 table 中的数据,将相同的值插入 CSV 文件 (payrate.csv)

发生了什么: 1.三个文件全部创建 2. XML 文件仅包含我程序中指定的 'root' 值 3. CSV文件完全为空 4. 程序没有返回任何错误。 tkinter GUI 加载并显示得很好

我已尝试搜索此问题,但我看到了类似的错误,但我找到的 none 解决方案解决了我遇到的问题。非常感谢有关此问题的任何指导。

我的猜测是,在填充 'rows' 列表之前我的连接以某种方式关闭,这导致了空数据。我只是不确定如何解决这个问题。

#!/usr/bin/env/python3
import csv
import os
import os.path as op
import sqlite3 as sq
from contextlib import closing
import xml.etree.ElementTree as et
import tkinter as tk
from tkinter import ttk

def checkDir(self):
    directory = op.dirname(op.abspath(__file__))
    path = op.join(directory, 'payrate.db') # Path of payrate.db
    DB_LOC = op.join(directory, 'payrate.db')
    conn = sq.connect(DB_LOC) # Create connection object
    c = conn.cursor() # Get a cursor object
    if os.path.exists(path) == False:
        # Database does not exist
        self.err['text'] = "Data not found. Creating the database..."
        # Payrate table string
        tableString = """Create Table payrate(
                        ID INTEGER not null primary key,
                        FIRST_NAME VARCHAR(30),
                        LAST_NAME VARCHAR(30),
                        PAYRATE DECIMAL(99999, 2)"""

        c.execute(tableString) # Create a table

        ## Insert rows of data into the table
        c.execute("INSERT INTO PAYRATE VALUES(0,'John', 'Nolan', 99999.99)")
        c.execute("INSERT INTO PAYRATE VALUES(1,'Jane', 'Doe', 99999.99)")
        c.execute("INSERT INTO PAYRATE VALUES(2,'Tom', 'McCune', 99999.99)")
        c.execute("INSERT INTO PAYRATE VALUES(3,'Tim', 'Guerin', 99999.99)")
        c.execute("INSERT INTO PAYRATE VALUES(4,'Sally', 'Pleas', 99999.99)")
        c.execute("INSERT INTO PAYRATE VALUES(5,'Miranda', 'Conrad', 99999.99)")
        self.err['text'] = "Database created successfully. Checking for XML..."
    # Database already existed 
    else:
        self.err['text'] = "Database loaded successfully. Checking for XML file..."

    # set a variable with the database contents for reuse
    rows = list(c.fetchall())

    # change path to the xml document and check for existence
    path = op.join(directory, 'payrate.xml')
    if os.path.exists(path) == False:
        # database created, copy data to xml
        self.err['text'] = "Data not found. Creating the XML file..."
        # select all data from the database
        root = et.Element('Payrates')
        root.set('version', '1.0')
        et.ElementTree(root).write('payrate.xml')
        for row in rows:
            employee = et.SubElement(root, 'Employee',
            {
                'ID':row['ID'],
                'FirstName':row['FIRST_NAME'],
                'LastName':row['LAST_NAME'],
                'PayRate':row['PAYRATE'],
            })
            et.ElementTree(employee).write('payrate.xml')

        self.err['text'] = "XML file created successfully. Checking for CSV..."
    # XML file already existed
    else:
        self.err['text'] = "XML file loaded successfully. Checking for CSV file"

    # update path and check for CSV file
    path = op.join(directory, 'payrate.csv')
    if os.path.exists(path) == False:
        # database/xml created, copy data to csv
        self.err['text'] = "Data not found. Generating the CSV file..."
        # Add a row in the csv file for each line in the database
        with open(path, "w", newline='') as csvfile:
            for row in rows:
                filewriter = csv.writer(csvfile)
                filewriter.writerow(row)
        self.err['text'] = "Data created successfully. We're set to go!"
    # CSV file already existed
    else:
        self.err['text'] = "All data loaded successfully. Please enter values and choose your option."

    # save results and close the database connection
    conn.commit()
    conn.close()

我在同事的帮助下解决了这个问题。

问题:在程序逻辑导致文件丢失之前,我打开了与 'payrate.db' 的连接。这样做的目的是创建一个空的 table,然后创建一个空的 .csv 和 .xml 文件。

此外,我没有为我的 fetchall 语句分配查询,结果失败了。