pyqt5 数据库相关操作

目标做链接数据库的数据维护小脚本,可查询下载上传更新数据库的数据

获取上传文件与下载文件路径

from PyQt5.QtWidgets import QFileDialog, QMessageBox

class Window_WH():
    def __init__(self):
        self.mainwindow = QWidget()

    def get_up_filenames(self):
        up_filename = QFileDialog.getOpenFileName(self.mainwindow, '选择文件', os.getcwd(), "Files(*.csv)")
        print(print(up_filename))
        if str(up_filename[0]) == "":
            QMessageBox.information(self.mainwindow, "提示", "没有选择上传文件")
            return ''
        else:
            return up_filename[0]

    # 保存文件函数
    def get_down_filename(self):
        down_filename = QFileDialog.getSaveFileName(self.mainwindow, "文件保存", os.getcwd(), "Files(*.csv)")
        print(down_filename)
        if str(down_filename[0]) == "":
            QMessageBox.information(self.mainwindow, "提示", "没有保存文件")  # 调用弹窗提示
            return ''
        else:
            return down_filename[0]

获取QSqlQueryModel中的数据

from pandas import DataFrame
from PyQt5.QtSql import QSqlQueryModel
from PyQt5.QtCore import Qt

# 连接数据库后
model = QSqlQueryModel()
model.setQuery("SELECT * FROM table")

def get_model_data(model: QSqlQueryModel):
    data = []
    for row in range(model.rowCount()):
        data.append([])
        for column in range(model.columnCount()):
            index = model.index(row, column)
            data[row].append(model.data(index))

    # 获取表头
    heads = [model.headerData(i, Qt.Horizontal) for i in range(model.columnCount())]
    df = DataFrame(data,columns=heads)
    return df

df = get_model_data(model)
posted @ 2022-10-01 18:08  meizhengchao  阅读(99)  评论(0编辑  收藏  举报