QT 访问 Postgresql 数据库:将查询结果绑定到结构体
以下是一个使用 QT 访问 Postgresql 数据库的示例代码,将查询结果绑定到结构体中:
#include <QCoreApplication>
#include <QtSql>
#include <QDebug>
// 定义结构体
struct Employee {
int id;
QString name;
QString position;
int salary;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 连接数据库
QSqlDatabase db = QSqlDatabase::addDatabase('QPSQL');
db.setHostName('localhost');
db.setDatabaseName('testdb');
db.setUserName('postgres');
db.setPassword('password');
if (!db.open()) {
qDebug() << 'Failed to connect to database.';
return 1;
}
// 声明查询语句
QSqlQuery query(db);
query.prepare('SELECT * FROM employees');
// 执行查询
if (!query.exec()) {
qDebug() << 'Failed to execute query.';
return 1;
}
// 用 QVector 存储结果
QVector<Employee> employees;
while (query.next()) {
// 绑定结果到结构体中
Employee employee;
employee.id = query.value(0).toInt();
employee.name = query.value(1).toString();
employee.position = query.value(2).toString();
employee.salary = query.value(3).toInt();
employees.append(employee);
}
// 打印结果
for (const auto &employee : employees) {
qDebug() << 'ID:' << employee.id << 'Name:' << employee.name << 'Position:' << employee.position << 'Salary:' << employee.salary;
}
return a.exec();
}
在这个示例中,我们首先使用 QSqlDatabase 类连接到 Postgresql 数据库,然后声明一个 QSqlQuery 对象 query,用来执行查询语句。我们将查询结果绑定到一个结构体 Employee 中,然后将每个结构体存储在一个 QVector 中。最后,我们遍历 QVector,打印所有结果。
原文地址: https://www.cveoy.top/t/topic/nVkW 著作权归作者所有。请勿转载和采集!