How to use databases in PyQt5?

Using databases in PyQt5 involves using Qt’s SQL module to connect and manipulate databases. Here is a simple example demonstrating how to connect to a SQLite database and execute queries in PyQt5.

from PyQt5 import QtSql

# 创建数据库连接
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('test.db')

if not db.open():
    print('无法打开数据库连接')
else:
    query = QtSql.QSqlQuery()
    query.exec_("CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT)")

    # 插入数据
    query.exec_("INSERT INTO person (name) VALUES ('Alice')")
    query.exec_("INSERT INTO person (name) VALUES ('Bob')")

    # 查询数据
    query.exec_("SELECT * FROM person")
    while query.next():
        id = query.value(0)
        name = query.value(1)
        print(f'id: {id}, name: {name}')

    # 关闭数据库连接
    db.close()

In this example, start by establishing a connection to a SQLite database, then perform various database operations such as creating tables, inserting data, and querying data. Finally, close the database connection.

It is important to note that PyQt5 provides the QtSql module for database operations, supporting various databases such as SQLite, MySQL, and PostgreSQL. When using different databases, it is necessary to adjust settings and operations accordingly based on the specific database type.

 

More tutorials

insertMany function for bulk insertion into a MongoDB database.(Opens in a new browser tab)

What operating systems does PyQt5 support?(Opens in a new browser tab)

How to add a menu bar in PyQt5?(Opens in a new browser tab)

What is the purpose of the QThread class in PyQt5?(Opens in a new browser tab)

How to create a file dialog in PyQt5?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *