一、环境
1、操作系统:win11
2、qt版本:6.5.2
3、PostgreSql版本:14.9
二、下载qbase源码
1、下载地址:https://github.com/qt/qtbase/tree/6.5.2
将下载的源码文件解压指定的的目录,找到src/plugins/sqldrivers根据自己的实际情况放置,本次我使用的目录如下:
三、编译驱动
1、编译文件配置
进入sqldrivers目录
(1)配置.make.conf文件
set(QT_REPO_MODULE_VERSION "6.5.2")# 开启pg插件
SET(FEATURE_sql_psql ON)#pg驱动头文件
SET(PostgreSQL_INCLUDE_DIR "E:/software/QT/src/pgsql14.9/include")#pg动态库引导文件
SET(PostgreSQL_LIBRARY "E:/software/QT/src/pgsql14.9/lib/libpq.lib")
(2)配置CmakeLists.txt
cmake_minimum_required(VERSION 3.16)
if (NOT CMAKE_PROJECT_NAME STREQUAL "QtBase" AND NOT CMAKE_PROJECT_NAME STREQUAL "Qt")include(.cmake.conf)project(QSQLiteDriverPluginsVERSION "${QT_REPO_MODULE_VERSION}"DESCRIPTION "Qt6 SQL driver plugins"HOMEPAGE_URL "https://qt.io/"LANGUAGES CXX C ASM)find_package(Qt6 ${PROJECT_VERSION} CONFIG REQUIRED COMPONENTSBuildInternalsCoreSql)qt_prepare_standalone_project()
else()qt_internal_upgrade_cmake_policies()
endif()qt_feature_module_begin(NO_MODULEPUBLIC_FILE "qtsqldrivers-config.h"PRIVATE_FILE "qtsqldrivers-config_p.h"
)include(configure.cmake)
add_subdirectory(psql)
2、QtCretor打开CmakeLists.txt
3、驱动编译
选择项目右键选择构建,编译成功输入输出日志如下
4、Qt的mingw配置驱动文件
将编译好的qsqlpsql.dll文件拷贝至qt的运行目录(我本机目录E:\software\QT\6.5.2\mingw_64\bin),仅仅拷贝这医个文件远远不够,还需要将postgresql运行目录下的几个文件拷贝到qt运行目录
libcrypto-1_1-x64.dll
libiconv-2.dll
libintl-9.dll
libpq.dll
libssl-1_1-x64.dll
四、连接数据库测试
void intiDb()
{QStringList drivers = QSqlDatabase::drivers();qDebug() << drivers;QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");db.setHostName("server200");db.setDatabaseName("qt_db");db.setUserName("postgres");db.setPassword("123456");bool isOk = db.open();qDebug() << (isOk?"连接postgresql成功":"连接postgresql失败") << (isOk?"":db.lastError().text()) ;QSqlQuery sqlQuery;sqlQuery.exec("SELECT id,name,age FROM t_test");while(sqlQuery.next()){qDebug() << sqlQuery.value("id").toInt() << " " << sqlQuery.value("name").toString() << "" << sqlQuery.value("age").toInt() ;}
至此大功告成