Qt postgresql driver not loaded windows

I have some trouble when I want to add a database.

    _dataBase = QSqlDatabase::addDatabase("QPSQL");

After calling this method I have an error:

QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7

I include to PATH variable paths to:

PostgreSQL\9.3\bin
PostgreSQL\9.3\lib
PostgreSQL\9.3\include

Also I copy folder sqldrivers to Debug folder. Also tried to copy dlls drom this folder to Debug. Doesn’t work either.

asked Oct 22, 2014 at 12:23

bin-bin's user avatar

2

I came here googling because I had the same problem in Windows.

In my case to solve the issue I had to install PostgreSQL for Windows 32 bits since my Qt target was MinGW 32 bits.

Additionally, I had to add the PATH to the PostgreSQL bin and lib directories so Qt could find the right .dlls.

@SET PATH=C:\Program Files (x86)\PostgreSQL\9.6\bin\;C:\Program Files (x86)\PostgreSQL\9.6\lib\;%PATH%

The PATH can be set before launching Qt Creator or using the Qt Creator itself via the Build Environment in the Projects pane.

answered Nov 12, 2016 at 0:49

Tarod's user avatar

TarodTarod

6,7725 gold badges44 silver badges50 bronze badges

Add the system variable QT_DEBUG_PLUGINS=1 if you want to get full information of why the QPSQL driver has not been loaded.

Probably you will discover that Qt is not able to find it. Copy and paste the output here to know what exactly happens.

Tarod's user avatar

Tarod

6,7725 gold badges44 silver badges50 bronze badges

answered Oct 22, 2014 at 13:47

0

Use depends.exe on qsqlpsql.dll and found that this dll need libpq.dll from PostgreSQL\9.3\libfolder. Add libpq.dll to Debug folder and it works:)

answered Oct 24, 2014 at 6:55

bin-bin's user avatar

bin-binbin-bin

5322 gold badges6 silver badges16 bronze badges

Try pip install PyQt5 event if you already installed it using conda or installer. It helped me.

Dijkgraaf's user avatar

Dijkgraaf

11.1k17 gold badges42 silver badges54 bronze badges

answered Jan 3, 2019 at 21:51

user10807076's user avatar

I got same problem with deploying Qt application (windeployqt didn’t help). I had to copy more .dlls (libcrypto-1_1-x64.dll, libiconv-2.dll, libintl-8.dll, libpq.dll, libssl-1_1-x64.dll, libwinpthread-1.dll) from postgreSQL bin path (c:\Program Files\PostgreSQL\12\bin) next to .exe file (according to dependency walker).

answered Nov 14, 2022 at 12:48

Ivan Kamensky's user avatar

Дано
ОС Windows 7 или 10 x64
Qt5.5.1 (mingw) (x86) или новее
PostgreSQL 10 или новее

Задача
Заставить разработанное на Qt приложение запускаться на машине без установленного Qt и PostgreSQL и подключаться к СУБД PostgreSQL.

При вызове QSqlDatabase::addDatabse(«QPSQL») программа пишет:

QSqlDatabase: QPSQL driver not loaded

QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7

либо вовсе:

QSqlDatabase: QPSQL driver not loaded

QSqlDatabase: available drivers:

Анализ

Как в общих чертах происходит работа с БД в Qt:
Функция QSqlDatabase::addDatabse живет в Qt5Sql.dll, и при вызове пытается динамически подгрузить qsqlpsql.dll, которая тянет за собой кучу других dll, часть из которых живет в составе PostgreSQL.

Разберемся, как решать эту и подобные проблемы, связанные с dll.

Принципиально существует два способа связывания dll и exe-файлов: явное и неявное. При загрузке SQL-драйверов Qt задействованы оба способа.
Сначала при запуске exe-файла происходит поиск и загрузка требуемых dll-библиотек, в т.ч. Qt5Sql.dll. Если какие-то библиотеки не найдены, то при запуске программы Windows сообщит об этом.

В процессе работы программы при вызове QSqlDatabase::addDatabse делается динамический поиск dll-файлов SQL-драйверов в определенных каталогах. Для драйвера QPSQL должна быть найдена библиотека qsqlpsql.dll, после чего выполняется попытка ее загрузки.

Для этого загружаются другие неявно связанные с ней dll-библиотеки вместе со своими зависимостями. Если всё дерево необходимых dll-библиотек найдено, то qsqlpsql.dll будет успешно загружена и Qt сможет использовать этот драйвер.

Но сложность в том, что при отсутствии какой-либо библиотеки Windows не выдаст красивого сообщения об этом и придется разбираться другими способами.

Разбираемся

Нам надо выяснить, какие dll-библиотеки требуются для работы программы и куда их нужно положить.

Для этого достаточно в общих чертах представлять, как Windows ищет dll, а именно, что сначала производится поиск в каталоге exe-файла, а в конце — по путям, указанным в переменной окружения PATH. PATH удобно использовать на машине разработчика, но этот вариант рассматривать не будем т.к. это не соответствует изначальной задаче. 

Также надо знать, в каких каталогах QSqlDatabase::addDatabse ищет драйверы SQL. Существуют способы указать Qt альтернативные пути, где искать плагины (в т.ч. SQL), но не будем заниматься и этим.

Исследуем

Используем Прекрасную программы DependencyWalker, которая показывает дерево зависимостей dll и exe-файлов.

Сначала открываем с помощью неё исполняемый файл программы и смотрим, какие dll-библиотеки должны быть доступны, ищем их в каталоге установки Qt и компилятора и кладем рядом с исполняемым файлом. Теперь программа должна запускаться и доходить до вызова QSqlDatabase::addDatabse.

Чтобы увидеть, где Qt ищет SQL-драйверы, добавляем переменную окружения QT_PLUGIN_PATH = 1 (например, в настройках параметров запуска приложения в QtCreator), запускаем программу и изучаем ее вывод. Кроме прочего должны быть примерно такие строки:

QFactoryLoader::QFactoryLoader() checking directory path «C:/Qt/Qt5.5.1/5.5/mingw492_32/plugins/sqldrivers»

QFactoryLoader::QFactoryLoader() checking directory path «C:/projects/build-foobar-Desktop-Release/release/sqldrivers»

Из них становится ясно, что по умолчанию Qt ищет SQL-драйверы в каталоге установки и в подкаталоге sqldrivers рядом с exe-файлом. Поэтому находим qsqlpsql.dll в каталоге установки Qt (примерно в C:\Qt\5.5.1\mingw491_32\bin\plugins\sqldrivers) и копируем в подкаталог sqldrivers рядом с exe-файлом.
Если все сделано верно, то после вызова QSqlDatabase::addDatabse должно вывестись:

QSqlDatabase: available drivers: QPSQL QPSQL7

Если не удалось, то попробовать положить qsqlpsql.dll в plugins/sqldrivers.

Далее с помощью DependencyWalker исследуем зависимости qsqlpsql.dll.

Кроме зависимостей от библиотек Qt и компилятора, будет зависимость от libpq.dll.

Проще всего взять libpq.dll из каталога установки PostgreSQL (примерно в C:\Program Files (x86)\PostgreSQL\10\bin). Здесь есть две важнейшие особенности:

1) разрядность libpq.dll должна совпадать с разрядностью приложения. Под Windows стандартный SDK Qt5 с официального сайта 32-разрядный. т.е. необходима 32-разрядная версия libpq.dll, которую можно взять из x86-версии PostgreSQL. Это не влияет на разрядность сервера PostgreSQL, к которому будет подключаться приложение;

2) libpq.dll необходимо располагать рядом с exe-файлом, а не рядом с qsqlpsql.dll. Все остальные dll, от которых зависит libpq.dll, необходимо класть также рядом с exe-файлом приложения.

Теперь все тем же DependencyWalker исследуем зависимости libpq.dll в каталоге установки PostgreSQL.

В зависимости от версии PostgreSQL у libpq.dll могут быть разные dll-зависимости. Находим их все в каталоге установки PostgreSQL и копируем рядом с exe-файлом. Не забываем пройтись по всем зависимостям всех добавляемых dll. 

Сравниваем

Из установленного PostgreSQL 9.4 нужно позаимствовать следующие библиотеки:

libpq.dll

ssleay32.dll

libeay32.dll

libintl-8.dll

libiconv-2.dll

Для PostgreSQL 10 набор уже другой:

libpq.dll

libssl-1_1.dll

libcrypto-1_1.dll

libintl-8.dll

libiconv-2.dll

Более новые версии PostgreSQL выпускаются только в редакции x64, поэтому для получения x86-версии libpq.dll и других библиотек, возможно, придется собирать их из исходников самостоятельно (я не пробовал).

Что еще
возможно, Вам, как и мне, потребуется откуда-то добыть msvcr120.dll (или что-то вроде того в новых версиях Windows и PostgreSQL) и тоже бросить рядом с exe-файлом.

Итого
У меня получилась следующая структура каталога простой консольной программы, выполняющей загрузку драйвера БД:

qpsqltest.exe

sqldrivers/qsqlpsql.dll

Qt5Core.dll

Qt5Sql.dll

libpq.dll

libssl-1_1.dll

libcrypto-1_1.dll

libintl-8.dll

libiconv-2.dll

libwinpthread-1.dll

libstdc++-6.dll

libgcc_s_dw2-1.dll

msvcr120.dll

Архив c примером на гуглодиске

If you’re trying to use Postgres with PyQt5/6 or PySide2/PySide6 you may have come across an issue with loading the driver.
Qt (correctly) lists the driver as available in Qt, but when trying to load it the load will fail. This is because the Qt
library depends on Postgres’ own library, which must be available in the path to load.

The following script will let you test if the Postgres library is loading correctly.

  • PyQt5
  • PyQt6
  • PySide2
  • PySide6

python

from PyQt5.QtSql import QSqlDatabase
from PyQt5.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PyQt6.QtSql import QSqlDatabase
from PyQt6.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PySide2.QtSql import QSqlDatabase
from PySide2.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PySide6.QtSql import QSqlDatabase
from PySide6.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

Executing the above script in a new command prompt will give the following
output (if Postgres is not accessible).

command

>python test.py
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7
Available drivers ['QSQLITE', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']
Unable to connect.
Last error Driver not loaded Driver not loaded

The list of «available drivers» shows the Qt drivers which are available in your PyQt5 (or PyQt6, or PySide2, or PySide6) installation. For example, in my installation the driver files are under site-packages\PyQt5\Qt5\plugins\sqldrivers

command

C:\Users\Martin\AppData\Local\Programs\Python\Python37\Lib\site-packages\PyQt5\Qt5\plugins\sqldrivers> dir

 Volume in drive C has no label.
 Volume Serial Number is 0A6A-65ED

 Directory of C:\Users\Martin\AppData\Local\Programs\Python\Python37\Lib\site-packages\PyQt5\Qt5\plugins\sqldrivers

02/12/2021  14:35    <DIR>          .
02/12/2021  14:35    <DIR>          ..
02/12/2021  14:35         1,412,080 qsqlite.dll
02/12/2021  14:35            98,288 qsqlodbc.dll
02/12/2021  14:35            79,856 qsqlpsql.dll
               3 File(s)      1,590,224 bytes
               2 Dir(s)  174,429,970,432 bytes free

The Driver not loaded error is occurring because the Qt Postgres driver cannot find the Postgres libraries. The Qt Postgres driver is a wrapper around these libraries, rather than a complete implementation of Postgres itself.

To get this working you need to ensure the required Postgres library files are available in your path.
You can do this by adding your Postgres installation bin folder to your path. For example, on my computer Postgres is installed under C:\Program Files\PostgreSQL\14\ (I’m using version 14). We need to add to the Postgres bin folder to the PATH as this contains libpq.dll (Postgres Access Library) which Qt needs.

command

SET PATH=%PATH%;C:\Program Files\PostgreSQL\14\bin

With that in place, running the script again will show that that driver has loaded successfully. The
connection still isn’t working, since it needs the username and password set. But if you get this far
you know the driver is working properly.

command

U:\home\martin\www\pythonguis\content\faq\qt-postgres-driver>python test.py
Available drivers ['QSQLITE', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']
Unable to connect.
Last error connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
QPSQL: Unable to connect

We can modify the test script to add your username and password to complete the connection.

  • PyQt5
  • PyQt6
  • PySide2
  • PySide6

python

from PyQt5.QtSql import QSqlDatabase
from PyQt5.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
db.setUserName("postgres")  # postgres is the default root username
db.setPassword("")    # add your password here
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PyQt6.QtSql import QSqlDatabase
from PyQt6.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
db.setUserName("postgres")  # postgres is the default root username
db.setPassword("")    # add your password here
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PySide2.QtSql import QSqlDatabase
from PySide2.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
db.setUserName("postgres")  # postgres is the default root username
db.setPassword("")    # add your password here
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

python

from PySide6.QtSql import QSqlDatabase
from PySide6.QtWidgets import QApplication

app = QApplication([])

db = QSqlDatabase("QPSQL")
db.setUserName("postgres")  # postgres is the default root username
db.setPassword("")    # add your password here
print("Available drivers", db.drivers())

if not db.open():
    print("Unable to connect.")
    print('Last error', db.lastError().text())
else:
    print("Connection to the database successful")

…and then the connection will complete as expected.

command

>python test-userpass.py
Available drivers ['QSQLITE', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']
Connection to the database successful

Over 10,000 developers have bought Create GUI Applications with Python & Qt!

[[ discount.discount_pc ]]% OFF for
the next [[ discount.duration ]]
[[discount.description ]]
with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses
with code [[ discount.coupon_code ]]

updated: this is what I got from QT_DEBUG_PLUGINS:

"The plugin 'D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlodbcd.dll' uses incompatible Qt library. (Cannot mix debug and release libraries.)" 
         not a plugin
QFactoryLoader::QFactoryLoader() looking at "D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsql.dll"
Found metadata in lib D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsql.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QPSQL7",
            "QPSQL"
        ]
    },
    "archreq": 0,
    "className": "QPSQLDriverPlugin",
    "debug": false,
    "version": 331264
}


Got keys from plugin meta data ("QPSQL7", "QPSQL")
QFactoryLoader::QFactoryLoader() looking at "D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsqld.dll"
Found metadata in lib D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsqld.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QPSQL7",
            "QPSQL"
        ]
    },
    "archreq": 1,
    "className": "QPSQLDriverPlugin",
    "debug": true,
    "version": 331264
}


"The plugin 'D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsqld.dll' uses incompatible Qt library. (Cannot mix debug and release libraries.)" 
         not a plugin
QFactoryLoader::QFactoryLoader() checking directory path "C:/Users/nkbar/Documents/build-myRPG_alpha-Desktop_Qt_5_14_0_MSVC2017_64bit-Release/Server/release/sqldrivers" ...
Cannot load library D:\Qt\5.14.0\msvc2017_64\plugins\sqldrivers\qsqlpsql.dll: The specified module could not be found.
QLibraryPrivate::loadPlugin failed on "D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsql.dll" : "Cannot load library D:\\Qt\\5.14.0\\msvc2017_64\\plugins\\sqldrivers\\qsqlpsql.dll: The specified module could not be found."
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7
QFactoryLoader::QFactoryLoader() checking directory path "D:/Qt/5.14.0/msvc2017_64/plugins/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "C:/Users/nkbar/Documents/build-myRPG_alpha-Desktop_Qt_5_14_0_MSVC2017_64bit-Release/Server/release/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "D:/Qt/5.14.0/msvc2017_64/plugins/accessiblebridge" ...
QFactoryLoader::QFactoryLoader() checking directory path "C:/Users/nkbar/Documents/build-myRPG_alpha-Desktop_Qt_5_14_0_MSVC2017_64bit-Release/Server/release/accessiblebridge" ...

I checked «D:\Qt\5.14.0\msvc2017_64\plugins\sqldrivers\qsqlpsqld.dll» and I did found the dll which the debugger reports as missing. And I am also confused about why it complains about «‘D:/Qt/5.14.0/msvc2017_64/plugins/sqldrivers/qsqlpsql.dll’ uses incompatible Qt library.

The kit I am using is msvc2017 64bit and the postgre I downloaded is also for 64bit.


Errors:
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7

OS: win10 64bit
qt: 5.14.0
kit: msvc2017 64bit
PostgreSQL: 12.1

Sqlite works well, but my project just can’t work with PostgreSQL.

I followed the official instruction: https://doc.qt.io/qt-5/sql-driver.html#qpsql

Got no error but still couldn’t connect to PostgreSQL. Same error messages saying that «QPSQL driver not loaded».

I have also tried other solutions from here and stackoverflow and reinstall my qt 4 times, No luck still. I am really frustrated now and don’t know what to do.

the .pro:

QT += core network gui widgets sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

QTPLUGIN += QPSQL
QT_DEBUG_PLUGINS=1

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

#INCLUDEPATH += "D:\psql\include"

#LIBS += "D:\psql\lib\libpq.lib"


SOURCES += \
    battle.cpp \
    creature.cpp \
    player.cpp \
    server.cpp \
    servermain.cpp \
    serverwindow.cpp \
    serverworker.cpp

HEADERS += \
    battle.h \
    creature.h \
    data_structs.h \
    player.h \
    server.h \
    serverwindow.h \
    serverworker.h

FORMS += \
    serverwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    resource.qrc

Qt, PostgreSQL

Здравствуйте.

Пытаюсь подключить PostgreSQL 9,6. Разрядность скорей всего 32.

Компилятор MinGW32.

В pro файле дописал

INCLUDEPATH += C:/Program Files (x86)/PostgreSQL/9.6/include

LIBS+= C:/Program Files (x86)/PostgreSQL/9.6/lib/libpq.dll

В проекте срр написал

QSqlDatabase SearchDB = QSqlDatabase::addDatabase(«QPSQL»);

При работе выдает ошибку:

QSqlDatabase: QPSQL driver not loaded

QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7

Скажите пожалуйста как правильно подключить PostgreSQL 9,6?

Вам это нравится? Поделитесь в социальных сетях!

  • Qt platform plugin windows ошибка как исправить
  • Qualcomm atheros ar3011 windows 10 x64
  • Qualcomm atheros ar9485 wireless network adapter скачать драйвер windows 10
  • Qt platform plugin windows 10 скачать
  • Qt designer python скачать windows 64