Константин К.
Очередной блог о решении возникающих проблем
30 мая 2017
QPSQL driver not loaded: развертывание Qt5+PostgreSQL-приложения на Windows
Дано
ОС Windows 7 x64
Qt5.5.1 (mingw) (x86)
PostgreSQL 9.5
Задача
Заставить приложение запускаться и подключаться к СУБД PostgreSQL на машине без установленного Qt и PostgreSQL.
Анализ
Как в общих чертах происходит работа с БД в Qt:
QSqlDatabase::addDatabse живет в Qt5Sql.dll, и при вызове пытается динамически подгрузить qsqlpsql.dll, который тянет за собой кучу других dll, часть из которых живет в составе PostgreSQL.
Решение
Прекрасная программа DependencyWalker позволяет проследить все дерево зависимостей от Qt5Sql.dll и от qsqlpsql.dll. Рассмотрим по порядку.
Qt5Sql.dll
Тут все просто. Если Ваша тестовая (или не очень) программа скомпилировалась и запустилась, то все зависимости Qt5Sql.dll удовлетворены по определению и все хорошо.
Поиск драйвера
Если QSqlDatabase::drivers среди прочего выдает QPSQL, то все хорошо, файл qsqlpsql.dll доступен.
Если нет, то его следует положить в папку «каталог_с_exe_файлом/plugins/sqldrivers/».
Взять драйвер qsqlpsql.dll можно примерно в «C:\Qt\5.5.1\mingw491_32\bin\plugins\sqldrivers» — точное положение зависит от версии Qt (в общем, поищите поиском). Если драйвера нет, то его следует собрать самому из исходников (инструкции есть в гугле).
Если Вы все еще тут, значит при попытке подключения к БД получается ошибка «driver not loaded» — значит процесс загрузки драйвера с его зависимостями провалился и проблема в том, что не ясно, из-за чего именно это произошло, поэтому идем дальше.
qsqlpsql.dll
Тут интереснее. qsqlpsql.dll, кроме прочего, зависит от библиотек, входящих в состав PostgreSQL. Значит надо сделать так, чтобы они были видны в момент загрузки драйвера.
Варианты:
— если установлен PostgreSQL, то можно добавить в системную переменную PATH путь к папке bin, находящейся внутри каталога установки PostgreSQL;
— если нет, то нужно раздобыть необходимые dll из состава PostgreSQL и положить их рядом с Вашим exe-файлом (именно рядом, а не в каких-либо подпапках).
В обоих случаях надо учитывать, что разрядность библиотек PostgreSQL должна соответствовать разрядности Qt и вашего приложения в частности. Т.е. если у Вас 32-разрядное приложение, то и dll надо брать из 32-разрядной версии PostgreSQL.
(при этом, естественно, не имеет значения разрядность сервера СУБД PostgreSQL, к которому Ваше приложение пытается подключиться)
Из установленного PostgreSQL нужно позаимствовать следующие библиотеки:
libpq.dll
ssleay32.dll
libeay32.dll
libintl-8.dll
libiconv-2.dll
Рекомендую пройтись DependencyWalker’ом от qsqlpsql.dll и libpq.dll чтобы быть уверенным, что в новых версиях PostgreSQL не появились новые зависимости.
Что еще
возможно, Вам, как и мне, потребуется откуда-то добыть msvcr120.dll (или что-то вроде того в новых версиях Windows, PostgreSQL, Qt) и тоже бросить рядом с вашим exe-файлом.
Итого
У меня получилась следующая структура каталога простой программы с GUI, выполняющей подключение к БД:
QPSQL driver not loaded
QSqlDatabase: QPSQL driver not loaded
Не пойму в чем дело, до этого на SQLite работало все хорошо. Решил перейти на Postgres. И тут.
QODBC (MS SQL SERVER) . Driver not loaded Driver not loaded
Собрал себе драйвер QODBC. mingw x86. QSqlDatabase::drivers() возвращает (QSQLITE, QMYSQL.
На машине клиента «QSQLITE» выдает: Driver not loaded Driver not loaded
#include #include #include #include .
Ошибка — Driver not loaded Driver not loaded
Собрал драйвер MySQL. Пытаюсь запустить простое приложение — подключиться к базе и выполнить sql -.
Решение
Samriel, откуда столь интересный список файлов на скриншоте? Чем вы руководствовались, определяя необходимость того или иного файла?
Еще у народа на форуме встречается мнение, что должна совпадать разрядность СУБД и Qt, но насколько это соответствует действительности для PostgreSQL, я не знаю.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.
Driver not loaded
не могу открыть базу данных, ошибка driver not loaded qt mingw 5.5 все драйвера есть QT += sql.
QT qmysql driver not loaded
Доброго времени суток вам! Следующая проблема: Решил поиграть с MySQL и qt. MySQL Server 8.0.
QMYSQL driver not loaded
Добрый день! Помогите решить проблему, над которой пыхчу второй день! Суть вот в чем,из своей.
QSQLITE driver not loaded
Проблема такая: все библиотеки на месте, даже программа их видит. Но не грузит. QSqldatabase.
Qpsql driver not loaded qt windows
Since I can’t build the MySQL driver, I try to make a connection to PostgreSQL database like I saw the QPSQL driver was available. But when I want to connect, I have got the message «QPSQL driver not loaded». I check in the directory C:\Qt\5.1.1\mingw48_32\plugins\sqldrivers and I have the good DLL : qsqlpsql.dll and qsqlpsqld.dll.
So why is the driver not loaded? What have we have to do?
Do you have the postgresql dll in your PATH environment variable ?
Which library excatly? The qsqlpsql.dll?
No, the dll from your PostgreSQL installation (pq.dll IIRC)
I don’t find any dll of this kind. I tried to copy evry dll in the postgreSQL folder into my application folder. But it didn’t work neither.
You can use Dependency Walker on your qsqlpsql.dll to check what dlls you need.
I have got the message:
Error: At least one required implicit or forwarded dependency was not found.
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
There is few missing dll:
LIBPQ.DLL
API-MS-WIN-CORE-COM-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL
API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL
DCOMP.DLL
IESHIMS.DLL
But where can I find all this dll?
You can safely ignore DCOMP and IESHIMS.
The API* should also not be of concern.
So you need to have LIBPQ.dll in your PATH.
What you can do is to go in the Projects pane of QtCreator, choose Run for your Kit and edit the PATH variable in «Run Environment», add the complete path to where libpq.dll can be located in front of the other paths (don’t forget the semi-colon at the end of your path)
Then you should be good to go
I add the «C:\Program Files\PostgreSQL\9.3\bin» directory into the Windows PATH environment variable (and restart the computer) but it doesn’t work. I still have the message «Driver not loaded».
I check back with depends.exe, and LIBPQ.DLL is not missing anymore.
But it display me the warning dialog saying:
Errors were detected when processing «c:\qt\mingw48_32\plugins\sqldrivers\QSQLPSQL.DLL». See the log wondow for details.
I still have the missing dependancy as before (except for LIBPQ.DLL)
There are some more Dll’s on which libpq depends. I guess these are
libssl32.dll
libeay32.dll
ssleay32.dll
I had the same problem but I just found the solution.
First I’m putting my environment conditions:
- Windows 8.1 Enterprise
- Qt 5.4
- PostgreSQL 8.4.22
Here is what I did:
- I downloaded the PostgreSQL from http://olex.openlogic.com/packages/postgresql/8.4.22-1
- I followed the instructions from this video https://www.youtube.com/watch?v=fBgJ9Azm_S0
- I used the 2nd method, which is creating the dll by myself but in my case I didn’t had to add the DEFINES += HAVE_STRUCT_TIMESPEC. It seems to me that’s for the PostgreSQL 9.X
- After I moved the new dlls I still had the same problem, but when read this post I put in the PATH var this two dir «C:\PostgreSQL\8.4\bin; C:\Qt\Qt5.4.0\5.4\mingw491_32\bin» and reboot it and voila problem solved
I hope this will also help you
I had the same problem but I just found the solution.
First I’m putting my environment conditions:
- Windows 8.1 Enterprise
- Qt 5.4
- PostgreSQL 8.4.22
Here is what I did:
- I downloaded the PostgreSQL from http://olex.openlogic.com/packages/postgresql/8.4.22-1
- I followed the instructions from this video https://www.youtube.com/watch?v=fBgJ9Azm_S0
- I used the 2nd method, which is creating the dll by myself but in my case I didn’t had to add the DEFINES += HAVE_STRUCT_TIMESPEC. It seems to me that’s for the PostgreSQL 9.X
- After I moved the new dlls I still had the same problem, but when read this post I put in the PATH var this two dir «C:\PostgreSQL\8.4\bin; C:\Qt\Qt5.4.0\5.4\mingw491_32\bin» and reboot it and voila problem solved
I hope this will also help you
Hi i just wanted to post an answer that I found that worked for me so that people in the future don’t have to deal as much on it as me on Windows,
With Qt Creator version 5,4, Compiler: MinGW 4.9.1 32bits and Database: PostgreSQL 9.4 on Windows 8.1 32bit and Windows 7 32bit.
Just copy «libeay32.dll» , «intl.dll» , «libpq.dll» , «ssleay32.dll«(if any of them are missing, add them) from the PostgreSQL’s bin folder to Qt’s bin (for me it looks like this: Qt\5.4\mingw491_32\bin).
Best of luck.
@Fenigor This worked for me right away. Vow. Thanks a lot.