PyQt5調入數據庫數據在表格中顯示


數據庫為Postgresql

import sys
from form import Ui_Form
from PyQt5.Qt import QWidget, QApplication,QTableWidgetItem
import psycopg2

class myform(QWidget,Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        self.btn1.clicked.connect(self.clear)
        self.btn2.clicked.connect(self.load)
        self.show()
        
    def clear(self):
        pass
    def load(self):
        conn=psycopg2.connect("dbname=test1_data user=jm password=123")
        cur=conn.cursor()
        cur.execute('select * from table1')
        rows=cur.fetchall()
        row=cur.rowcount  #取得記錄個數,用於設置表格的行數
        vol=len(rows[0])  #取得字段數,用於設置表格的列數
        cur.close()
        conn.close()
        
        self.table.setRowCount(row)
        self.table.setColumnCount(vol)
        
        for i in range(row):
            for j in range(vol):
                temp_data=rows[i][j]  #臨時記錄,不能直接插入表格
                data=QTableWidgetItem(str(temp_data)) #轉換后可插入表格
                self.table.setItem(i,j,data)
        
app=QApplication(sys.argv)
w=myform()
app.exec_()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM