qt6 自带pg数据库驱动:
pro文件加个说明:
引用位置添加(按需添加,这里我就大致加一下):
test code: 理想情况当然是要用pool,这里只是演示调用而已
QSqlError DbTool::testConnection(const QString &driver, const QString &dbName, const QString &host, const QString &user, const QString &passwd, int port)
{
// 为每个连接创建一个唯一的标识符
static int cCount = 0;
// 存储数据库连接的错误信息
QSqlError err;
// 添加数据库连接并设置连接参数
db = QSqlDatabase::addDatabase(driver, QString("myChat%1").arg(++cCount));
db.setDatabaseName(dbName);
db.setHostName(host);
db.setPort(port);
// 尝试打开数据库连接
if (!db.open(user, passwd)) {
// 如果打开失败,获取错误信息并移除数据库连接
err = db.lastError();
db = QSqlDatabase();
QSqlDatabase::removeDatabase(QString("mychat%1").arg(cCount));
}else{
// QMessageBox::information(0, QObject::tr("Database Information"),
// "Database is connected successfully");
qDebug() << "Database is connected successfully";
//query table sys_doctors
QSqlQuery query(db);
bool b=query.exec("SELECT user_name FROM sys_doctors");
if (b)
{
qDebug() << "query success";
}
else
{
qDebug() << "query failed";
}
while (query.next())
{
QString name = query.value(0).toString();
qDebug() << name;
}
db.close();
}
// 返回数据库连接的错误信息(如果有)
return err;
}
调用代码:
QSqlError err = dbtool->testConnection("QPSQL", "myChat", "localhost", "postgres", "1", 5432);
if (err.type() != QSqlError::NoError)
{
qDebug() << err.text();
}
else
{
qDebug() << "Database is connected successfully";
}