将方法连接到自定义QListView小部件 - PyQt5& PostgreSQL的

时间:2016-11-09 12:59:54

标签: postgresql python-3.x pyqt5

我有一个简单的Qt应用程序,它使用自定义小部件添加和列出从QListView中的postgresql数据库检索到的记录。我在设置按钮(每个列表项实例的左下角)时遇到一些困难,这将有效地使用记录主键(实例)从db中删除记录

from PyQt5 import QtCore, QtWidgets
import psycopg2
import sys
import dbAPP_GUI
import listItem_GUI


class dbAPP(QtWidgets.QMainWindow, dbAPP_GUI.Ui_MainWindow):
    def __init__(self, parent=None):
        super(dbAPP, self).__init__(parent)
        self.setupUi(self)

        self.conn = psycopg2.connect(database="Name", user="anthony@primeinstr.co.za"
                                     , password="14581458", host="127.0.0.1")

        self.ListItemLine = listItem()

        # ==============
        # CONNECTIONS
        # ==============
        self.btn_save.clicked.connect(self.writeData)
        self.tabWidget.currentChanged.connect(self.fetchData)
        self.btn_go.clicked.connect(self.searchData)


    # =============
    # METHODS
    # =============
    def writeData(self):
        name = self.name_lineEdit.text()
        surn = self.surname_lineEdit.text()
        age = self.age_lineEdit.text()
        address = self.address_lineEdit.text()

        if len(name) > 0:
            c = self.conn.cursor()
            c.execute(" INSERT INTO info (name, surname, age, address)"
                      "VALUES (%s, %s, %s, %s)", (name, surn, age, address))
            self.conn.commit()

            QtWidgets.QMessageBox.information(self, "Notice", "Information was successfully written to database")

            self.name_lineEdit.clear()
            self.surname_lineEdit.clear()
            self.age_lineEdit.clear()
            self.address_lineEdit.clear()
        else:
            QtWidgets.QMessageBox.warning(self, "Warning", "The name field is empty, please enter a value")


    def fetchData(self):
        self.listWidget.clear()
        lineNo = 0
        c = self.conn.cursor()
        c.execute("SELECT * FROM info;")
        listing = c.fetchall()

        for i in listing:

            name = (str(i[:1]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            surn = (str(i[1:2]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            age = (str(i[2:3]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            address = (str(i[3:4]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            ID = (str(i[4:5]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            nameSurn = name + " " + surn

            lineNo += 1

            label = listItem()
            label.num_label.setText(str(lineNo))
            label.nameSurn_label.setText(nameSurn)
            label.age_label.setText(age)
            label.address_label.setText(address)
            label.id_label.setText(ID)

            x = QtWidgets.QListWidgetItem()
            x.setSizeHint(QtCore.QSize(280, 60))

            self.listWidget.addItem(x)
            self.listWidget.setItemWidget(x, label)

            label.show()


    def searchData(self):
        self.listWidget_2.clear()
        lineNo = 0
        c = self.conn.cursor()
        c.execute("SELECT * FROM info;")
        results = c.fetchall()

        for i in results:
            name = (str(i[:1]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            surn = (str(i[1:2]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            age = (str(i[2:3]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            address = (str(i[3:4]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
            nameSurn = name + " " + surn

            if str(self.search_lineEdit.text()).lower() == name.lower()\
                    or str(self.search_lineEdit.text()).lower() == surn.lower()\
                    or str(self.search_lineEdit.text()).lower() == address.lower():

                lineNo += 1

                label = listItem()
                label.num_label.setText(str(lineNo))
                label.nameSurn_label.setText(nameSurn)
                label.age_label.setText(age)
                label.address_label.setText(address)

                x = QtWidgets.QListWidgetItem()
                x.setSizeHint(QtCore.QSize(280, 60))

                self.listWidget_2.addItem(x)
                self.listWidget_2.setItemWidget(x, label)

                label.show()

# ======================================================================================================================

class listItem(QtWidgets.QWidget, listItem_GUI.Ui_lineItem):
    def __init__(self, parent=None):
        super(listItem, self).__init__(parent)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setupUi(self)

        self.btn_del.clicked.connect(self.delData)


    def delData(self):
        ID = self.id_label.text()
        print(ID)

        c = psycopg2._ext.connection.cursor()
        c.execute("DELETE FROM info WHERE id=(%s)", (ID))

# ======================================================================================================================
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
main = dbAPP()
main.show()
List = listItem()
List.hide()
sys.exit(app.exec_())

目前它失败了,因为方法中的光标对象" DelData"需要一个论点。但是,如果这是正确的方法,我可以诚实地说不。因此,如果有人有任何更好的建议,那也可以。我只想用PyQt,postgreSQL和Python找到我的脚:))

1 个答案:

答案 0 :(得分:0)

execute的第二个参数是序列或映射。但是你实际上是在传递一个字符串,因为元组主要由逗号定义,而不是括号。

所以你应该这样做:

c.execute("DELETE FROM info WHERE id=%s", (ID,)) # tuple

或者这个:

c.execute("DELETE FROM info WHERE id=%s", [ID]) # list

或者这个:

c.execute("DELETE FROM info WHERE id=%(ID)s", {'ID': ID}) # dict