数据库PostgreSQL可以方便用在Qt5程序中。
1.下载安装PostgreSQL-13.1
https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
3.建立数据库
2.确认相应的driver存在
3.在.pro中添加sql支持
QT += core gui svg opengl network sql
4.新建一个UI
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;
}
运行结果:
多谢,亲爱的美美。