本文主要是介绍Qt5.14.2 操作PostgreSQL 记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Qt5.14.2中操作PostgreSQL数据库.
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>// 初始化数据库连接QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");//qDebug() << "aaaa";db.setHostName("localhost"); // 数据库服务器地址db.setDatabaseName("postgres"); // 数据库名db.setPort(5433);db.setUserName("postgres"); // 用户名db.setPassword("system"); // 密码// 打开数据库连接if (!db.open()) {qDebug() << "数据库连接失败:" << db.lastError().text();// return -1;}// 创建一个QSqlQuery对象来执行SQL语句QSqlQuery query;// 执行 SQL 语句if (query.exec("CREATE TABLE IF NOT EXISTS people (id SERIAL PRIMARY KEY, name VARCHAR(255))")) {qDebug() << "Table created successfully";} else {qDebug() << "Error creating table:" << query.lastError().text();}// 插入数据if (query.exec("INSERT INTO people (name) VALUES ('John Doe')")) {qDebug() << "Data inserted successfully";} else {qDebug() << "Error inserting data:" << query.lastError().text();}// 查询数据query.exec("SELECT * FROM people");while (query.next()) {qDebug() << "ID:" << query.value(0) << " - Name:" << query.value(1).toString();}// 关闭数据库连接db.close();
这篇关于Qt5.14.2 操作PostgreSQL 记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!