基于PyQt5 postgreSQL实现简单的数据插入、数据表格查询。
运行前需要安装psycopg2 模块,配置好postgerSQL。
先看效果图:
第1列为日期时间、第2列为自增1的编号、第3到第5列为设定的字符串。数据查询时,根据创建表的设定框名字查询该表的数据。
主程序代码
1 # -*- coding: utf-8 -*- 2 import sys 3 import psycopg2 4 import time,datetime 5 from PyQt5.QtWidgets import QApplication, QMainWindow,QWidget,QMessageBox,QTableWidgetItem 6 from TableView_test import Ui_dataBaseForm 7 8 9 class MyMain(QMainWindow,Ui_dataBaseForm): 10 conn = psycopg2.connect(database="postgres", user="postgres", password="0818", host="localhost", port="5432") 11 cursor = conn.cursor() 12 13 def __init__(self): 14 super().__init__() 15 self.setupUi(self) ## 初始化运行A窗口类下的 setupUi 函数 16 self.db_create.clicked.connect(self.createBase) #创建数据库表 17 self.db_delete.clicked.connect(self.deleteBase) #删除表格 18 self.db_insert.clicked.connect(self.dbWrit) #插入数据 19 self.db_delete_row.clicked.connect(self.deleteRow) #删除行 20 self.date_select.clicked.connect(self.dateSelect) #查询输出 21 self.db_export.clicked.connect(self.excelExport) #导出CSV 22 23 24 25 #报警提示框 26 def alarmMessageBox(self,alarm): 27 self.alarm = alarm 28 reply = QMessageBox.information(self, "提示框", self.alarm, QMessageBox.Yes , 29 QMessageBox.Yes) 30 31 #创建表格 32 def createBase(self): 33 try: 34 self.dbName = self.db_create_edit.text()#设置表名 35 MyMain.cursor.execute("CREATE TABLE %s ( \ 36 date timestamp without time zone NOT NULL, \ 37 id serial NOT NULL, \ 38 line1 CHAR(6) NOT NULL,\ 39 line2 CHAR(6) NOT NULL,\ 40 line3 CHAR(6) NOT NULL,\ 41 PRIMARY KEY (date));" % (self.dbName)) ## 创建表SQL命令 42 MyMain.conn.commit() 43 self.alarmMessageBox("创建表格成功!") 44 except Exception as exc: 45 self.alarmMessageBox(str(exc)) ##触发报警框 46 MyMain.conn.commit() ## 给数据库,开启新的事物块。 47 48 #删除表格 49 def deleteBase(self): 50 try: 51 self.dbName = self.db_delete_edit.text()#设置表名 52 MyMain.cursor.execute("DROP TABLE %s " % (self.dbName)) ## 创建execu test 数据库SQL命令 53 MyMain.conn.commit() 54 self.alarmMessageBox("删除表格完成!") 55 except Exception as exc: 56 self.alarmMessageBox(str(exc)) 57 MyMain.conn.commit() 58 59 #写入数据 60 def dbWrit(self): 61 self.dbName = self.db_create_edit.text() 62 self.text = self.db_writ.text().split() #读取界面框数据 63 # print(self.text) 64 print(len(self.text)) 65 if len(self.text) != 3: 66 self.alarmMessageBox("数据为 %d 个,不符合要求。" % (len(self.text))) 67 else: 68 try: 69 MyMain.cursor.execute( "INSERT INTO {0} (date,line1,line2,line3) VALUES((SELECT now()),'{1}', '{2}' , '{3}')" 70 .format(self.dbName, self.text[0],self.text[1], self.text[2])) 71 MyMain.conn.commit() 72 except Exception as exc: 73 self.alarmMessageBox(str(exc)) 74 MyMain.conn.commit() 75 #删除最后一行 76 def deleteRow(self): 77 self.dbName = self.db_create_edit.text() 78 try: 79 MyMain.cursor.execute("DELETE FROM {0} WHERE date= (SELECT max(date) FROM {0})".format(self.dbName)) 80 MyMain.conn.commit() 81 self.alarmMessageBox("删除最后一行成功!") 82 except Exception as exc: 83 self.alarmMessageBox(str(exc)) 84 MyMain.conn.commit() 85 #查询的条件 86 def rogatoryCondition(self): 87 self.startTime = self.date_start.dateTime().toString("yyyy-MM-dd hh:mm:ss") 88 self.endTime = self.date_end.dateTime().toString("yyyy-MM-dd hh:mm:ss") 89 90 self.dbName = self.db_create_edit.text() 91 self.select = "SELECT date, id ,line1,line2,line3 FROM {0} WHERE date > '{1}' and date < '{2}'".format( 92 self.dbName, 93 self.startTime, 94 self.endTime) 95 return self.select 96 97 #查询输出 98 def dateSelect(self): 99 self.condition = self.rogatoryCondition() 100 try: 101 MyMain.cursor.execute(self.condition) 102 self.data = MyMain.cursor.fetchall() 103 self.rowNum = len(self.data) #获取查询到的行数 104 self.columnNum = len(self.data[0]) #获取查询到的列数 105 106 self.dataView.setRowCount(self.rowNum) #设置表格行数 107 self.dataView.setColumnCount(self.columnNum) 108 109 for i, da in enumerate( self.data): 110 for j in range(self.columnNum): 111 self.itemContent = QTableWidgetItem(( '%s' ) % (da[j])) 112 self.dataView.setItem(i,j,self.itemContent ) 113 self.alarmMessageBox("查询完成!") 114 except Exception as exc: 115 self.alarmMessageBox(str(exc)) 116 MyMain.conn.commit() 117 118 def excelExport(self): 119 self.condition = self.rogatoryCondition() 120 MyMain.cursor.execute("COPY( {0} ) TO 'D:/ExceptionData.csv' with csv header".format(self.condition)) 121 self.alarmMessageBox("导出成功!") 122 123 124 125 126 127 128 129 if __name__ == "__main__": 130 app = QApplication(sys.argv) 131 A1 = MyMain() 132 A1.show() 133 sys.exit(app.exec_())
UI文件代码,TableView_test.py 代码
1 # -*- coding: utf-8 -*- 2 3 # Form implementation generated from reading ui file 'TableView_test.ui' 4 # 5 # Created by: PyQt5 UI code generator 5.11.3 6 # 7 # WARNING! All changes made in this file will be lost! 8 9 from PyQt5 import QtCore, QtGui, QtWidgets 10 11 class Ui_dataBaseForm(object): 12 def setupUi(self, dataBaseForm): 13 dataBaseForm.setObjectName("dataBaseForm") 14 dataBaseForm.resize(1127, 754) 15 font = QtGui.QFont() 16 font.setBold(False) 17 font.setWeight(50) 18 dataBaseForm.setFont(font) 19 dataBaseForm.setAutoFillBackground(False) 20 self.groupBox = QtWidgets.QGroupBox(dataBaseForm) 21 self.groupBox.setGeometry(QtCore.QRect(870, 80, 231, 141)) 22 font = QtGui.QFont() 23 font.setBold(False) 24 font.setWeight(50) 25 self.groupBox.setFont(font) 26 self.groupBox.setStyleSheet("") 27 self.groupBox.setObjectName("groupBox") 28 self.layoutWidget = QtWidgets.QWidget(self.groupBox) 29 self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 211, 101)) 30 self.layoutWidget.setObjectName("layoutWidget") 31 self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget) 32 self.gridLayout.setContentsMargins(0, 0, 0, 0) 33 self.gridLayout.setObjectName("gridLayout") 34 self.db_create = QtWidgets.QPushButton(self.layoutWidget) 35 self.db_create.setObjectName("db_create") 36 self.gridLayout.addWidget(self.db_create, 0, 1, 1, 1) 37 self.db_delete_edit = QtWidgets.QLineEdit(self.layoutWidget) 38 font = QtGui.QFont() 39 font.setFamily("微软雅黑") 40 font.setPointSize(12) 41 font.setBold(False) 42 font.setItalic(False) 43 font.setWeight(50) 44 self.db_delete_edit.setFont(font) 45 self.db_delete_edit.setLayoutDirection(QtCore.Qt.LeftToRight) 46 self.db_delete_edit.setStyleSheet("") 47 self.db_delete_edit.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) 48 self.db_delete_edit.setObjectName("db_delete_edit") 49 self.gridLayout.addWidget(self.db_delete_edit, 1, 0, 1, 1) 50 self.db_delete = QtWidgets.QPushButton(self.layoutWidget) 51 self.db_delete.setObjectName("db_delete") 52 self.gridLayout.addWidget(self.db_delete, 1, 1, 1, 1) 53 self.db_create_edit = QtWidgets.QLineEdit(self.layoutWidget) 54 font = QtGui.QFont() 55 font.setFamily("微软雅黑") 56 font.setPointSize(12) 57 font.setBold(False) 58 font.setItalic(False) 59 font.setWeight(50) 60 self.db_create_edit.setFont(font) 61 self.db_create_edit.setLayoutDirection(QtCore.Qt.LeftToRight) 62 self.db_create_edit.setStyleSheet("") 63 self.db_create_edit.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) 64 self.db_create_edit.setObjectName("db_create_edit") 65 self.gridLayout.addWidget(self.db_create_edit, 0, 0, 1, 1) 66 self.groupBox_2 = QtWidgets.QGroupBox(dataBaseForm) 67 self.groupBox_2.setGeometry(QtCore.QRect(870, 270, 231, 171)) 68 self.groupBox_2.setObjectName("groupBox_2") 69 self.layoutWidget1 = QtWidgets.QWidget(self.groupBox_2) 70 self.layoutWidget1.setGeometry(QtCore.QRect(10, 20, 211, 141)) 71 self.layoutWidget1.setObjectName("layoutWidget1") 72 self.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget1) 73 self.gridLayout_2.setContentsMargins(0, 0, 0, 0) 74 self.gridLayout_2.setObjectName("gridLayout_2") 75 self.A_title_3 = QtWidgets.QLabel(self.layoutWidget1) 76 font = QtGui.QFont() 77 font.setPointSize(11) 78 self.A_title_3.setFont(font) 79 self.A_title_3.setObjectName("A_title_3") 80 self.gridLayout_2.addWidget(self.A_title_3, 3, 0, 1, 1) 81 self.date_select = QtWidgets.QPushButton(self.layoutWidget1) 82 self.date_select.setObjectName("date_select") 83 self.gridLayout_2.addWidget(self.date_select, 5, 0, 1, 1) 84 self.A_title_2 = QtWidgets.QLabel(self.layoutWidget1) 85 font = QtGui.QFont() 86 font.setPointSize(11) 87 self.A_title_2.setFont(font) 88 self.A_title_2.setObjectName("A_title_2") 89 self.gridLayout_2.addWidget(self.A_title_2, 0, 0, 1, 1) 90 self.date_start = QtWidgets.QDateTimeEdit(self.layoutWidget1) 91 font = QtGui.QFont() 92 font.setPointSize(12) 93 font.setBold(True) 94 font.setWeight(75) 95 self.date_start.setFont(font) 96 self.date_start.setDateTime(QtCore.QDateTime(QtCore.QDate(2019, 1, 1), QtCore.QTime(3, 2, 3))) 97 self.date_start.setCalendarPopup(True) 98 self.date_start.setObjectName("date_start") 99 self.gridLayout_2.addWidget(self.date_start, 1, 0, 1, 1) 100 self.date_end = QtWidgets.QDateTimeEdit(self.layoutWidget1) 101 font = QtGui.QFont() 102 font.setPointSize(12) 103 font.setBold(True) 104 font.setWeight(75) 105 self.date_end.setFont(font) 106 self.date_end.setDateTime(QtCore.QDateTime(QtCore.QDate(2019, 3, 1), QtCore.QTime(2, 7, 11))) 107 self.date_end.setCalendarPopup(True) 108 self.date_end.setObjectName("date_end") 109 self.gridLayout_2.addWidget(self.date_end, 4, 0, 1, 1) 110 self.groupBox_3 = QtWidgets.QGroupBox(dataBaseForm) 111 self.groupBox_3.setGeometry(QtCore.QRect(870, 450, 231, 171)) 112 self.groupBox_3.setObjectName("groupBox_3") 113 self.layoutWidget2 = QtWidgets.QWidget(self.groupBox_3) 114 self.layoutWidget2.setGeometry(QtCore.QRect(10, 20, 211, 111)) 115 self.layoutWidget2.setObjectName("layoutWidget2") 116 self.gridLayout_3 = QtWidgets.QGridLayout(self.layoutWidget2) 117 self.gridLayout_3.setContentsMargins(0, 0, 0, 0) 118 self.gridLayout_3.setObjectName("gridLayout_3") 119 self.db_print = QtWidgets.QPushButton(self.layoutWidget2) 120 self.db_print.setObjectName("db_print") 121 self.gridLayout_3.addWidget(self.db_print, 1, 0, 1, 1) 122 self.db_export = QtWidgets.QPushButton(self.layoutWidget2) 123 self.db_export.setObjectName("db_export") 124 self.gridLayout_3.addWidget(self.db_export, 0, 0, 1, 1) 125 self.layoutWidget3 = QtWidgets.QWidget(dataBaseForm) 126 self.layoutWidget3.setGeometry(QtCore.QRect(10, 630, 851, 33)) 127 self.layoutWidget3.setObjectName("layoutWidget3") 128 self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget3) 129 self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) 130 self.horizontalLayout_2.setObjectName("horizontalLayout_2") 131 self.A_title = QtWidgets.QLabel(self.layoutWidget3) 132 font = QtGui.QFont() 133 font.setPointSize(10) 134 self.A_title.setFont(font) 135 self.A_title.setObjectName("A_title") 136 self.horizontalLayout_2.addWidget(self.A_title) 137 self.db_writ = QtWidgets.QLineEdit(self.layoutWidget3) 138 font = QtGui.QFont() 139 font.setFamily("新宋体") 140 font.setPointSize(10) 141 font.setBold(False) 142 font.setItalic(False) 143 font.setWeight(50) 144 self.db_writ.setFont(font) 145 self.db_writ.setLayoutDirection(QtCore.Qt.LeftToRight) 146 self.db_writ.setStyleSheet("") 147 self.db_writ.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) 148 self.db_writ.setObjectName("db_writ") 149 self.horizontalLayout_2.addWidget(self.db_writ) 150 self.db_insert = QtWidgets.QPushButton(self.layoutWidget3) 151 self.db_insert.setObjectName("db_insert") 152 self.horizontalLayout_2.addWidget(self.db_insert) 153 self.db_delete_row = QtWidgets.QPushButton(self.layoutWidget3) 154 self.db_delete_row.setObjectName("db_delete_row") 155 self.horizontalLayout_2.addWidget(self.db_delete_row) 156 self.dataView = QtWidgets.QTableWidget(dataBaseForm) 157 self.dataView.setGeometry(QtCore.QRect(10, 80, 851, 541)) 158 self.dataView.setObjectName("dataView") 159 #self.dataView.setColumnCount(0) 160 #self.dataView.setRowCount(0) 161 162 self.retranslateUi(dataBaseForm) 163 QtCore.QMetaObject.connectSlotsByName(dataBaseForm) 164 165 def retranslateUi(self, dataBaseForm): 166 _translate = QtCore.QCoreApplication.translate 167 dataBaseForm.setWindowTitle(_translate("dataBaseForm", "TableView数据库视图-liangfu")) 168 self.groupBox.setTitle(_translate("dataBaseForm", "基本操作")) 169 self.db_create.setText(_translate("dataBaseForm", "创建表格")) 170 self.db_delete_edit.setText(_translate("dataBaseForm", "dataBase")) 171 self.db_delete.setText(_translate("dataBaseForm", "删除表格")) 172 self.db_create_edit.setText(_translate("dataBaseForm", "dataBase")) 173 self.groupBox_2.setTitle(_translate("dataBaseForm", "查找数据")) 174 self.A_title_3.setText(_translate("dataBaseForm", "结束时间:")) 175 self.date_select.setText(_translate("dataBaseForm", "查询")) 176 self.A_title_2.setText(_translate("dataBaseForm", "开始时间:")) 177 self.date_start.setDisplayFormat(_translate("dataBaseForm", "yyyy-MM-dd hh:mm:ss")) 178 self.date_end.setDisplayFormat(_translate("dataBaseForm", "yyyy-MM-dd hh:mm:ss")) 179 self.groupBox_3.setTitle(_translate("dataBaseForm", "导出保存")) 180 self.db_print.setText(_translate("dataBaseForm", "打印")) 181 self.db_export.setText(_translate("dataBaseForm", "导出为Excel文档")) 182 self.A_title.setText(_translate("dataBaseForm", "输入数值(空格隔开):")) 183 self.db_writ.setText(_translate("dataBaseForm", "0.1023 0.1233 0.1214")) 184 self.db_insert.setText(_translate("dataBaseForm", "插入一行")) 185 self.db_delete_row.setText(_translate("dataBaseForm", "删除一行"))