【问题标题】:Issues converting data from sqlite3 to csv, xml using python3使用 python3 将数据从 sqlite3 转换为 csv、xml 的问题
【发布时间】:2020-09-03 18:01:39
【问题描述】:

*注意 - 这是一个任务,而不是提供一个解决方案,如果你能指出我在哪里弄乱了我的代码,那将不胜感激。

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

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

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

我已尝试对此进行搜索,并且看到了类似的错误,但我找到的解决方案都没有解决我看到的问题。对此问题的任何指导将不胜感激。

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

#!/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()

【问题讨论】:

    标签: python-3.x sqlite csv xml.etree


    【解决方案1】:

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

    问题:在程序逻辑导致文件丢失之前,我打开了与“payrate.db”的连接。这样做会导致创建一个空表,以及随后的空 .csv 和 .xml 文件。

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

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      相关资源
      最近更新 更多