PyQt5 Quick Start (eight) PyQt5 database operations

PyQt5 Quick Start (eight) PyQt5 database operations

A, SQLite database

1, SQLite Introduction

SQLite is a lightweight database, to achieve self-sufficiency, serverless, zero-configuration, transactional SQL database engine, primarily as a small desktop databases and database applications mobile applications.
Official Website:
https://www.sqlite.org

2, SQLite common operation

Create a database file, perform the SQLite command line mode after creation.
sqlite3 DatabaseName.db
View database file that already exists in the implementation of SQLite command line mode:
.databases
Open the database file already exists, and if the database file does not exist, it is created.
sqlite3 DatabaseName.db
View help information in the SQLite command line mode to perform:
.help
Create a table in SQLite command line mode execution:
create table person(id integer primary key, name text);
insert data into the table:
insert into person(id, name) values(1, "zhangsan");
query:
select * from person;
Structured Query table:
.schema person

3, SQLite Management Tools

There are several open source SQLite and good DBMS (database management system) that provides an interface operating SQLite database.
SQLiteStudio is a very professional SQLite database management software, compact, powerful, supporting Chinese, free installation.
SQLiteStudio Download:
https://sqlitestudio.pl/index.rvt?act=download

Second, connect to the database

1, database drivers

In PyQt, QSqlDatabase class connect to a database, the database may be used with a different driver interacting with the database instance representing a QSqlDatabase a database connection. Available database drivers as follows:
QDB2 IBM the DB2 driver
QMYSQL MySQL driver
QOCI Oracle Call Interface Driver
QODBC ODBC drivers (including SQL Server MS)
QPSQL PostgreSQL driver
QSQLITE SQLite3 drivers
QSQLITE2 SQLite2 driver

2, QSqlDatabase conventional method

QSqlDatabase common method is as follows:
addDataBase: Set connection to the database database-driven type
setDatabaseName: database name set connected
setHostName: Host Name set up a database where
setUserName: Specifies the user name connected
setPassword: set the connection object password
commit: commit the transaction, if implementation of successful return True.
rollback: rollback database transactions
close: Close the database connection

3, database connection instance

import sys
from PyQt5.QtSql import QSqlDatabase
from PyQt5.QtCore import *

if __name__ == "__main__":
    app = QCoreApplication(sys.argv)
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("/home/user/test.db")
    if db.open():
        print("open DB success.")
    sys.exit(app.exec_())

Third, execute SQL statements

QSqlQuery has a function to perform and manipulate SQL statements can be executed DDL and DML SQL query type, QSqlQuery.exec_()used to perform SQL operations.

import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtCore import *

def createDB():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("/home/user/test.db")
    if db.open():
        query = QSqlQuery()
        query.exec_("create table person(id int primary key, name varchar(20), address varchar(30))")
        query.exec_("insert into person values(1, 'Bauer', 'beijing')")
        query.exec_("insert into person values(2, 'Jack', 'shanghai')")
        query.exec_("insert into person values(3, 'Alex', 'chengdu')")

        db.close()

if __name__ == "__main__":
    app = QCoreApplication(sys.argv)
    createDB()
    sys.exit(app.exec_())

After executing the SQL statement, if there is no other database, you need to use db.close close the database connection because the database connection resources are limited, you no longer use the database connection must be closed, otherwise the database connection resources will eventually be depleted, causing the program unable to connect to the database correctly.
If you need to read the data in the database and PyQt window displays, it is necessary to open the database during initialization of the window, close the connection when the window is closed.

import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("/home/user/test.db")
        self.db.open()

    def closeEvent(self, event):
        self.db.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Fourth, the database model view

The QSqlTableModel Qt is an advanced interface that provides a readable and writable data model, and for reading data stored in a single table, the table can display in QTableView database. When connected to a database, the table is provided seTable queried using setFilter function to set the filter conditions, and then use the select function query operation. SetEditerStrategy function can be used to set policy editor, can edit the policy settings as follows:
QSqlTableModel.OnFieldChange: real-time updates all changes to the database
QSqlTableModel.OnRowChange: When the user selects a different row to be updated on the current line
QSqlTableModel.OnManuallSubmit: manual commit, not automatic submit

import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("/home/user/test.db")
        self.db.open()
        self.model = QSqlTableModel()
        self.initializedModel()

        self.tableView = QTableView()
        self.tableView.setModel(self.model)

        self.layout = QVBoxLayout()
        addButton = QPushButton("add")
        deleteButton = QPushButton("delete")
        hLayout = QHBoxLayout()
        hLayout.addWidget(addButton)
        hLayout.addWidget(deleteButton)
        self.layout.addWidget(self.tableView)
        self.layout.addLayout(hLayout)
        self.setLayout(self.layout)
        self.resize(600, 400)

        addButton.clicked.connect(self.onAddRow)
        deleteButton.clicked.connect(self.onDeleteRow)

    def initializedModel(self):
        self.model.setTable("person")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.select()
        self.model.setHeaderData(0, Qt.Horizontal, "ID")
        self.model.setHeaderData(1, Qt.Horizontal, "Name")
        self.model.setHeaderData(2, Qt.Horizontal, "Address")

    def onAddRow(self):
        self.model.insertRows(self.model.rowCount(), 1)
        self.model.submit()

    def onDeleteRow(self):
        self.model.removeRow(self.tableView.currentIndex().row())
        self.model.submit()
        self.model.select()

    def closeEvent(self, event):
        self.db.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Fifth, paging query

1, data preparation

Paging uses the data for the student information student table, you can use the command line using SQLite SQL statement to insert, you can use Python to create tables and insert data.

db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("/home/user/test.db")
if not db.open():
    return False
query = QSqlQuery()
query.exec_("create table student(id int primary key, name varchar(20), sex varchar(8), age int);")

query.exec_("insert into student values(1, 'Bauer', 'Man', 25)")
query.exec_("insert into student values(2, 'Alex', 'Man', 24)")
query.exec_("insert into student values(3, 'Mary', 'Female', 23)")
query.exec_("insert into student values(4, 'Jack', 'Man', 25)")
query.exec_("insert into student values(5, 'xiaoming', 'Man', 24)")
query.exec_("insert into student values(6, 'xiaohong', 'Female', 23)")
query.exec_("insert into student values(7, 'xiaowang', 'Man', 25)")
query.exec_("insert into student values(8, 'xiaozhang', 'Man', 25)")
query.exec_("insert into student values(9, 'xiaoli', 'Man', 25)")
query.exec_("insert into student values(10, 'xiaohan', 'Man', 25)")

2, tabbed window

Tabbed window includes a label, a front, a rear, jump button and the like.

import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class DataGrid(QWidget):
    def __init__(self, parent=None):
        super(DataGrid, self).__init__(parent)
        # 数据库连接
        self.db = None
        # 布局管理器
        self.layout = QVBoxLayout()
        # 查询模型
        self.queryModel = QSqlQueryModel()
        # 表格视图
        self.tableView = QTableView()
        self.tableView.setModel(self.queryModel)
        #
        self.totalPageLabel = QLabel()
        self.currentPageLabel = QLabel()
        self.switchPageLineEdit = QLineEdit()
        self.prevButton = QPushButton("Prev")
        self.nextButton = QPushButton("Next")
        self.switchPageButton = QPushButton("Switch")
        self.currentPage = 0
        self.totalPage = 0
        self.totalRecordCount = 0
        self.pageRecordCount = 5

    def initUI(self):
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.layout.addWidget(self.tableView)

        hLayout = QHBoxLayout()
        hLayout.addWidget(self.prevButton)
        hLayout.addWidget(self.nextButton)
        hLayout.addWidget(QLabel("跳转到"))
        self.switchPageLineEdit.setFixedWidth(40)
        hLayout.addWidget(self.switchPageLineEdit)
        hLayout.addWidget(QLabel("页"))
        hLayout.addWidget(self.switchPageButton)
        hLayout.addWidget(QLabel("当前页:"))
        hLayout.addWidget(self.currentPageLabel)
        hLayout.addWidget(QLabel("总页数:"))
        hLayout.addWidget(self.totalPageLabel)
        hLayout.addStretch(1)

        self.layout.addLayout(hLayout)
        self.setLayout(self.layout)

        self.setWindowTitle("DataGrid")
        self.resize(600, 300)

    def closeEvent(self, event):
        self.db.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DataGrid()
    window.initUI()
    window.show()
    sys.exit(app.exec_())

PyQt5 Quick Start (eight) PyQt5 database operations

3, pagination query implementation

The student reads the database tables, tabular data model initialization.

import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import re

class DataGrid(QWidget):
    def __init__(self, parent=None):
        super(DataGrid, self).__init__(parent)
        # 声明数据库连接
        self.db = None
        # 布局管理器
        self.layout = QVBoxLayout()
        # 查询模型
        self.queryModel = QSqlQueryModel()
        # 表格视图
        self.tableView = QTableView()
        self.tableView.setModel(self.queryModel)
        #
        self.totalPageLabel = QLabel()
        self.currentPageLabel = QLabel()
        self.switchPageLineEdit = QLineEdit()
        self.prevButton = QPushButton("Prev")
        self.nextButton = QPushButton("Next")
        self.switchPageButton = QPushButton("Switch")
        # 当前页
        self.currentPage = 1
        # 总页数
        self.totalPage = None
        # 总记录数
        self.totalRecordCount = None
        # 每页记录数
        self.pageRecordCount = 4

        self.initUI()
        self.initializedModel()
        self.setUpConnect()
        self.updateStatus()

    def initUI(self):
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.layout.addWidget(self.tableView)

        hLayout = QHBoxLayout()
        hLayout.addWidget(self.prevButton)
        hLayout.addWidget(self.nextButton)
        hLayout.addWidget(QLabel("跳转到"))
        self.switchPageLineEdit.setFixedWidth(40)
        hLayout.addWidget(self.switchPageLineEdit)
        hLayout.addWidget(QLabel("页"))
        hLayout.addWidget(self.switchPageButton)
        hLayout.addWidget(QLabel("当前页:"))
        hLayout.addWidget(self.currentPageLabel)
        hLayout.addWidget(QLabel("总页数:"))
        hLayout.addWidget(self.totalPageLabel)
        hLayout.addStretch(1)

        self.layout.addLayout(hLayout)
        self.setLayout(self.layout)

        self.setWindowTitle("DataGrid")
        self.resize(600, 300)

    def setUpConnect(self):
        self.prevButton.clicked.connect(self.onPrevPage)
        self.nextButton.clicked.connect(self.onNextPage)
        self.switchPageButton.clicked.connect(self.onSwitchPage)

    def initializedModel(self):
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("/home/user/test.db")
        if not self.db.open():
            return False
        self.queryModel.setHeaderData(0, Qt.Horizontal, "ID")
        self.queryModel.setHeaderData(1, Qt.Horizontal, "Name")
        self.queryModel.setHeaderData(2, Qt.Horizontal, "Sex")
        self.queryModel.setHeaderData(3, Qt.Horizontal, "Age")
        # 获取表的所有记录数
        sql = "SELECT * FROM student"
        self.queryModel.setQuery(sql, self.db)
        self.totalRecordCount = self.queryModel.rowCount()
        if self.totalRecordCount % self.pageRecordCount == 0:
            self.totalPage = self.totalRecordCount / self.pageRecordCount
        else:
            self.totalPage = int(self.totalRecordCount / self.pageRecordCount) + 1
        # 显示第1页
        sql = "SELECT * FROM student limit %d,%d" % (0, self.pageRecordCount)
        self.queryModel.setQuery(sql, self.db)

    def onPrevPage(self):
        self.currentPage -= 1
        limitIndex = (self.currentPage - 1) * self.pageRecordCount
        self.queryRecord(limitIndex)
        self.updateStatus()

    def onNextPage(self):
        self.currentPage += 1
        limitIndex = (self.currentPage - 1) * self.pageRecordCount
        self.queryRecord(limitIndex)
        self.updateStatus()

    def onSwitchPage(self):
        szText = self.switchPageLineEdit.text()
        pattern = re.compile('^[0-9]+$')
        match = pattern.match(szText)
        if not match:
            QMessageBox.information(self, "提示", "请输入数字.")
            return
        if szText == "":
            QMessageBox.information(self, "提示", "请输入跳转页面.")
            return
        pageIndex = int(szText)
        if pageIndex > self.totalPage or pageIndex < 1:
            QMessageBox.information(self, "提示", "没有指定的页,清重新输入.")
            return

        limitIndex = (pageIndex - 1) * self.pageRecordCount
        self.queryRecord(limitIndex)
        self.currentPage = pageIndex
        self.updateStatus()

    # 根据分页查询记录
    def queryRecord(self, limitIndex):
        sql = "SELECT * FROM student limit %d,%d" % (limitIndex, self.pageRecordCount)
        self.queryModel.setQuery(sql)

    # 更新空间状态
    def updateStatus(self):
        self.currentPageLabel.setText(str(self.currentPage))
        self.totalPageLabel.setText(str(self.totalPage))
        if self.currentPage <= 1:
            self.prevButton.setEnabled(False)
        else:
            self.prevButton.setEnabled(True)

        if self.currentPage >= self.totalPage:
            self.nextButton.setEnabled(False)
        else:
            self.nextButton.setEnabled(True)

    # 界面关闭时关闭数据库连接
    def closeEvent(self, event):
        self.db.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DataGrid()
    window.show()
    sys.exit(app.exec_())

PyQt5 Quick Start (eight) PyQt5 database operations

Guess you like

Origin blog.51cto.com/9291927/2424320