SoFunction
Updated on 2025-05-15

QT operates PostgreSQL database and implements the functions of adding, deleting, modifying and checking

1. Environmental preparation

1. Install PostgreSQL

Make sure PostgreSQL is installed and the test database is created.

2. Install the Qt development environment

Make sure the Qt development environment (Qt Creator or command line tool) is installed.

3. Configure Qt connection PostgreSQL

Add in the project file (.pro):

QT += sql

2. Connect to PostgreSQL database

1. Basic connection method

#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QDebug>
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    // Create a database connection    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    
    // Set connection parameters    ("localhost");      // Host name    (5432);                 // Port    ("testdb");     // Database name    ("postgres");       // username    ("password");       // password    
    // Open the connection    if (!()) {
        qDebug() << "Database connection failed:" << ().text();
        return -1;
    }
    
    qDebug() << "Successfully connected to the database";
    
    // Close the connection    ();
    
    return ();
}

2. Use the connection pool (recommended)

// Create a connection poolQSqlDatabase createConnectionPool(const QString &connectionName) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", connectionName);
    ("localhost");
    (5432);
    ("testdb");
    ("postgres");
    ("password");
    
    if (!()) {
        qCritical() << "Creating a connection pool failed:" << ().text();
        return QSqlDatabase();
    }
    
    return db;
}
 
// Get the connectionQSqlDatabase getConnection(const QString &connectionName) {
    QSqlDatabase db = QSqlDatabase::database(connectionName);
    if (!()) {
        if (!()) {
            qCritical() << "Finished connection:" << ().text();
            return QSqlDatabase();
        }
    }
    return db;
}
 
// Release the connectionvoid releaseConnection(const QString &connectionName) {
    QSqlDatabase::removeDatabase(connectionName);
}

3. Implement the operation of adding, deleting, modifying and checking

1. Create a test table

First create a test table in PostgreSQL:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    position VARCHAR(50),
    salary NUMERIC(10, 2),
    hire_date DATE
);

2. Insert data (Add)

bool insertEmployee(QSqlDatabase &db, const QString &name, 
                    const QString &position, double salary, 
                    const QDate &hireDate) {
    QSqlQuery query(db);
    
    // Use preprocessing statements to prevent SQL injection    ("INSERT INTO employees (name, position, salary, hire_date) "
                  "VALUES (:name, :position, :salary, :hire_date)");
    
    (":name", name);
    (":position", position);
    (":salary", salary);
    (":hire_date", hireDate);
    
    if (!()) {
        qDebug() << "Insert data failed:" << ().text();
        return false;
    }
    
    return true;
}

3. Query data (Query)

3.1 Query a single record

QSqlRecord getEmployeeById(QSqlDatabase &db, int id) {
    QSqlQuery query(db);
    ("SELECT * FROM employees WHERE id = :id");
    (":id", id);
    
    if (!() || !()) {
        qDebug() << "Inquiry failed:" << ().text();
        return QSqlRecord();
    }
    
    return ();
}

3.2 Query all records

QList<QSqlRecord> getAllEmployees(QSqlDatabase &db) {
    QList<QSqlRecord> employees;
    QSqlQuery query(db);
    ("SELECT * FROM employees ORDER BY id");
    
    while (()) {
        (());
    }
    
    return employees;
}

3.3 Querying using model (Qt SQL model)

QSqlTableModel *createEmployeeModel(QObject *parent = nullptr) {
    QSqlTableModel *model = new QSqlTableModel(parent);
    model-&gt;setTable("employees");
    model-&gt;select();
    
    // Set the table header    model-&gt;setHeaderData(1, Qt::Horizontal, tr("Name"));
    model-&gt;setHeaderData(2, Qt::Horizontal, tr("Position"));
    model-&gt;setHeaderData(3, Qt::Horizontal, tr("Salary"));
    model-&gt;setHeaderData(4, Qt::Horizontal, tr("Hire Date"));
    
    return model;
}

4. Update data (Update)

bool updateEmployee(QSqlDatabase &amp;db, int id, 
                    const QString &amp;name, const QString &amp;position, 
                    double salary, const QDate &amp;hireDate) {
    QSqlQuery query(db);
    ("UPDATE employees SET name = :name, position = :position, "
                  "salary = :salary, hire_date = :hire_date WHERE id = :id");
    
    (":name", name);
    (":position", position);
    (":salary", salary);
    (":hire_date", hireDate);
    (":id", id);
    
    if (!()) {
        qDebug() &lt;&lt; "Update employees failed:" &lt;&lt; ().text();
        return false;
    }
    
    return true;
}

5. Delete data (Delete)

bool deleteEmployee(QSqlDatabase &amp;db, int id) {
    QSqlQuery query(db);
    ("DELETE FROM employees WHERE id = :id");
    (":id", id);
    
    if (!()) {
        qDebug() &lt;&lt; "Delete employees failed:" &lt;&lt; ().text();
        return false;
    }
    
    return true;
}

4. Complete example

1. Use the console program to demonstrate CRUD operations

#include &lt;QCoreApplication&gt;
#include &lt;QtSql/QSqlDatabase&gt;
#include &lt;QtSql/QSqlQuery&gt;
#include &lt;QtSql/QSqlError&gt;
#include &lt;QtSql/QSqlRecord&gt;
#include &lt;QDebug&gt;
#include &lt;QDate&gt;
 
bool openDatabase(QSqlDatabase &amp;db) {
    db = QSqlDatabase::addDatabase("QPSQL");
    ("localhost");
    (5432);
    ("testdb");
    ("postgres");
    ("password");
    
    if (!()) {
        qDebug() &lt;&lt; "Database connection failed:" &lt;&lt; ().text();
        return false;
    }
    return true;
}
 
void closeDatabase(QSqlDatabase &amp;db) {
    ();
}
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    QSqlDatabase db;
    if (!openDatabase(db)) {
        return -1;
    }
    
    // Insert data    QSqlQuery query(db);
    ("INSERT INTO employees (name, position, salary, hire_date) "
                  "VALUES (:name, :position, :salary, :hire_date)");
    
    (":name", "Zhang San");
    (":position", "Development Engineer");
    (":salary", 15000.00);
    (":hire_date", QDate::currentDate());
    
    if (!()) {
        qDebug() &lt;&lt; "Insert failed:" &lt;&lt; ().text();
    } else {
        qDebug() &lt;&lt; "Insert successfully, ID:" &lt;&lt; ().toInt();
    }
    
    // Query data    QSqlQuery selectQuery(db);
    ("SELECT * FROM employees ORDER BY id");
    
    while (()) {
        QSqlRecord record = ();
        qDebug() &lt;&lt; "ID:" &lt;&lt; ("id").toInt()
                 &lt;&lt; "Name:" &lt;&lt; ("name").toString()
                 &lt;&lt; "Position:" &lt;&lt; ("position").toString()
                 &lt;&lt; "Salary:" &lt;&lt; ("salary").toDouble()
                 &lt;&lt; "Organization Date:" &lt;&lt; ("hire_date").toDate();
    }
    
    // Update data    ("UPDATE employees SET salary = :salary WHERE id = :id");
    (":salary", 16000.00);
    (":id", 1); // Assume that the employee with ID 1    
    if (!()) {
        qDebug() &lt;&lt; "Update failed:" &lt;&lt; ().text();
    } else {
        qDebug() &lt;&lt; "Update Successfully";
    }
    
    // Delete data    ("DELETE FROM employees WHERE id = :id");
    (":id", 1); // Assume that you want to delete an employee with ID 1    
    if (!()) {
        qDebug() &lt;&lt; "Delete failed:" &lt;&lt; ().text();
    } else {
        qDebug() &lt;&lt; "Delete successfully";
    }
    
    closeDatabase(db);
    return ();
}

2. Use Qt Widgets to implement the GUI interface

// 
#ifndef EMPLOYEEFORM_H
#define EMPLOYEEFORM_H
 
#include &lt;QWidget&gt;
#include &lt;QSqlTableModel&gt;
#include &lt;QDataWidgetMapper&gt;
 
QT_BEGIN_NAMESPACE
namespace Ui { class EmployeeForm; }
QT_END_NAMESPACE
 
class EmployeeForm : public QWidget
{
    Q_OBJECT
 
public:
    EmployeeForm(QWidget *parent = nullptr);
    ~EmployeeForm();
 
private slots:
    void on_addButton_clicked();
    void on_saveButton_clicked();
    void on_deleteButton_clicked();
    void on_refreshButton_clicked();
 
private:
    Ui::EmployeeForm *ui;
    QSqlTableModel *model;
    QDataWidgetMapper *mapper;
};
 
#endif // EMPLOYEEFORM_H
 
// 
#include ""
#include "ui_employeeform.h"
#include &lt;QSqlDatabase&gt;
#include &lt;QSqlError&gt;
#include &lt;QMessageBox&gt;
 
EmployeeForm::EmployeeForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::EmployeeForm)
{
    ui-&gt;setupUi(this);
 
    // Connect to the database    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    ("localhost");
    (5432);
    ("testdb");
    ("postgres");
    ("password");
 
    if (!()) {
        QMessageBox::critical(this, "mistake", "Unable to connect to database: " + ().text());
        return;
    }
 
    // Create a model    model = new QSqlTableModel(this, db);
    model-&gt;setTable("employees");
    model-&gt;select();
 
    // Set the table header    model-&gt;setHeaderData(1, Qt::Horizontal, tr("Name"));
    model-&gt;setHeaderData(2, Qt::Horizontal, tr("Position"));
    model-&gt;setHeaderData(3, Qt::Horizontal, tr("Salary"));
    model-&gt;setHeaderData(4, Qt::Horizontal, tr("Order date"));
 
    // Set up view    ui-&gt;tableView-&gt;setModel(model);
    ui-&gt;tableView-&gt;setEditTriggers(QAbstractItemView::DoubleClicked);
 
    // Set up the data mapper    mapper = new QDataWidgetMapper(this);
    mapper-&gt;setModel(model);
    mapper-&gt;addMapping(ui-&gt;nameEdit, 1);
    mapper-&gt;addMapping(ui-&gt;positionEdit, 2);
    mapper-&gt;addMapping(ui-&gt;salaryEdit, 3);
    mapper-&gt;addMapping(ui-&gt;hireDateEdit, 4);
 
    // Connect signal slot    connect(ui-&gt;tableView-&gt;selectionModel(), &amp;QItemSelectionModel::currentRowChanged,
            this, [this](const QModelIndex &amp;current, const QModelIndex &amp;) {
                mapper-&gt;setCurrentModelIndex(current);
            });
}
 
EmployeeForm::~EmployeeForm()
{
    delete ui;
}
 
void EmployeeForm::on_addButton_clicked()
{
    int row = model-&gt;rowCount();
    model-&gt;insertRow(row);
    ui-&gt;tableView-&gt;selectRow(row);
    mapper-&gt;setCurrentIndex(row);
    ui-&gt;nameEdit-&gt;setFocus();
}
 
void EmployeeForm::on_saveButton_clicked()
{
    if (!model-&gt;submitAll()) {
        QMessageBox::warning(this, "mistake", "Save failed: " + model-&gt;lastError().text());
    } else {
        model-&gt;database().transaction();
        if (model-&gt;submitAll()) {
            model-&gt;database().commit();
            QMessageBox::information(this, "success", "Data saved successfully");
        } else {
            model-&gt;database().rollback();
            QMessageBox::warning(this, "mistake", "Save failed: " + model-&gt;lastError().text());
        }
    }
}
 
void EmployeeForm::on_deleteButton_clicked()
{
    QModelIndex index = ui-&gt;tableView-&gt;currentIndex();
    if (()) {
        int ret = QMessageBox::question(this, "confirm", "Are you sure you want to delete this record?",
                                        QMessageBox::Yes | QMessageBox::No);
        if (ret == QMessageBox::Yes) {
            model-&gt;removeRow(());
            if (!model-&gt;submitAll()) {
                QMessageBox::warning(this, "mistake", "Delete failed: " + model-&gt;lastError().text());
                model-&gt;revertAll();
            }
        }
    }
}
 
void EmployeeForm::on_refreshButton_clicked()
{
    model-&gt;select();
}

V. Advanced features

1. Transaction processing

bool performTransaction(QSqlDatabase &amp;db) {
    ();
    
    QSqlQuery query(db);
    bool success = true;
    
    // Perform multiple operations    if (!("INSERT INTO employees (...) VALUES (...)" )) {
        success = false;
    }
    
    if (!("UPDATE ...")) {
        success = false;
    }
    
    if (success) {
        ();
    } else {
        ();
    }
    
    return success;
}

2. Batch insertion

bool batchInsertEmployees(QSqlDatabase &db, const QList<QVariantList> &employees) {
    QSqlDatabase::database().transaction();
    
    QSqlQuery query(db);
    ("INSERT INTO employees (name, position, salary, hire_date) "
                  "VALUES (?, ?, ?, ?)");
    
    foreach (const QVariantList &employee, employees) {
        (employee);
        if (!()) {
            QSqlDatabase::database().rollback();
            return false;
        }
    }
    
    QSqlDatabase::database().commit();
    return true;
}

3. Use stored procedures

bool callStoredProcedure(QSqlDatabase &amp;db, int employeeId) {
    QSqlQuery query(db);
    ("CALL update_employee_salary(:id, :percentage)");
    (":id", employeeId);
    (":percentage", 10); // Increase 10%    
    if (!()) {
        qDebug() &lt;&lt; "Calling stored procedure failed:" &lt;&lt; ().text();
        return false;
    }
    
    return true;
}

6. Frequently Asked Questions

1. Connection failed

  • Check whether the PostgreSQL service is running
  • Verify connection parameters (host name, port, database name, user name, password)
  • Check firewall settings
  • Make sure the PostgreSQL client library is installed

2. Chinese garbled

// Set encodingQTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

Or specify the encoding in the connection string:

("client_encoding=UTF8");

3. Performance optimization

  • Use preprocessing statements
  • Batch operation instead of single operation
  • Use transactions reasonably
  • Create indexes for common queries

7. Summary

Qt provides powerful and flexible database access functions, and the Qt SQL module can easily implement the addition, deletion, modification and query operations of PostgreSQL databases. This article introduces how to implement from basic connections to advanced features and provides a complete code example. In actual development, the appropriate implementation method can be selected according to project needs, and combined with transaction processing, batch operation and other technologies to improve application performance.

The above is the detailed content of QT operating PostgreSQL database and implementing the functions of adding, deleting, modifying and checking. For more information about QT operating PostgreSQL addition, deleting, modifying and checking, please pay attention to my other related articles!