天天看點

Qt5資料庫PostgreSQL應用1

資料庫PostgreSQL可以友善用在Qt5程式中。

1.下載下傳安裝PostgreSQL-13.1

https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

Qt5資料庫PostgreSQL應用1

3.建立資料庫

Qt5資料庫PostgreSQL應用1

2.确認相應的driver存在

Qt5資料庫PostgreSQL應用1

3.在.pro中添加sql支援

QT       += core gui svg opengl network sql
           

4.建立一個UI

Qt5資料庫PostgreSQL應用1

5.代碼:

SqlDialog.h

#ifndef SQLDIALOG_H
#define SQLDIALOG_H

#include <QDialog>

namespace Ui {
class SqlDialog;
}

class SqlDialog : public QDialog
{
    Q_OBJECT

public:
    explicit SqlDialog(QWidget *parent = nullptr);
    ~SqlDialog();

private:
    Ui::SqlDialog *ui;
};

#endif // SQLDIALOG_H
           

SqlDialog.cpp

#include "sqldialog.h"
#include "ui_sqldialog.h"

#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>

SqlDialog::SqlDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SqlDialog)
{
    ui->setupUi(this);

    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName("127.0.0.1");
    db.setUserName("postgres");
    db.setPassword("postgres");
    db.setDatabaseName("postgres");

    if(db.open())
    {
        QSqlQuery query;
        if(query.exec("SELECT name, age, gender, married FROM employee"))
        {
            while(query.next())
            {
                qDebug() <<  query.value(0) << query.value(1) << query.value(2) << query.value(3);
                ui->label_Name->setText(query.value(0).toString());
                ui->label_Age->setText(query.value(1).toString());
                ui->comboBoxGender->setCurrentIndex(query.value(2).toInt());
                ui->checkBoxMarried->setChecked(query.value(3).toBool());
            }
        }
        else
        {
            qDebug() << query.lastError().text();
        }
        db.close();
    }
    else
    {
        qDebug() << "Failed to connect to database.";
    }
}

SqlDialog::~SqlDialog()
{
    delete ui;
}
           

運作結果:

Qt5資料庫PostgreSQL應用1

多謝,親愛的美美。