Database error driver not loaded

First: I am using Qt v5.3.1 with MinGW 4.8.2, and Window 7 32bit platform. When run my application in windows 7, I found it is working fine in connect to database only if Qt environment is install...

First: I am using Qt v5.3.1 with MinGW 4.8.2, and Window 7 32bit platform.

When run my application in windows 7, I found it is working fine in connect to database only if Qt environment is installed, also when move the same application to another platform like windows xp by Virtual PC, unfortunately I found the connection to database fail too, and an error message appears driver not loaded, but the application works fine but without connection to database.

My attempts:

  • I have used QSqlDatabase::drivers() to check if sqlite supported
    in the system, and the result was, sqlite database
    supported with many other types.

  • I have used isValid() to check if there is a valid driver, but the
    function return false, and this indicates that the database type is
    not available or could not be loaded.

The following is the code that I use:

database.h

class database
{
public:
    static QSqlDatabase db;
    static QString dbPath;
    database();

    static void connect();
    static bool openConnection();
    static void CloseConnection();
    static void removeDB();
};

database.cpp

QSqlDatabase database::db = QSqlDatabase::addDatabase("QSQLITE");
QString database::dbPath = "";

database::database(){
}

void database::connect(){
    database::dbPath = "database.db";
    database::db.setDatabaseName(database::dbPath);
}

void database::CloseConnection(){
    database::db.close();
}

void database::removeDB(){
    database::db.removeDatabase(database::db.defaultConnection);
}

Also I have checked if the database file exists or not, and also I have opened the connection to database.

database::connect();
  if(QFile::exists(database::dbPath)){
      if(database::db.open()){
          ui->label->setText(ui->label->text() + "Connected.");
          QSqlQuery qry;
          qry.prepare("SELECT * FROM users");
          qry.exec();
          while(qry.next()){
              ui->listWidget->addItem(qry.value("username").toString());
              ui->listWidget->item(ui->listWidget->count()-1)->setData(Qt::UserRole, qry.value("id").toString());
            }
          database::CloseConnection();
        }else{
          ui->label->setText(ui->label->text() + "Failed to connect to database");
        }
    }else{
      ui->label->setText(ui->label->text() + "Database file does not found");
    }

I don’t know what’s the problem in the connection with database, everything is alright, and there is no missing files in my application, and the database file beside the executable file.

How to solve this problem ?

This topic has been deleted. Only users with topic management privileges can see it.

  • Hello everyone, this is yet another post on the dreaded error when trying to connect to a database from Qt, but a bit different.

    I am on an up-to-date Debian testing with Qt installed to /opt from the online installer.
    I am trying to write a program that connects to a database but the connection fails with error «Driver not loaded». Now, I’ve seen a lot of similar discussions but I wish to point out that this one is different from the ones that I’ve seen so far. In particular, I used to have the «regular» error due to a linking issue in libqsqlmysql.so but then I followed instruction online, recompiled it an substituted the original file.
    After that, the error message that I get changed and now my code, which reads

    db.addDatabase("QMYSQL");
    db.setDatabaseName("SomeDatabase");
    if (not db.open())
    {
        qDebug() << db.lastError().text();
    }
    

    simply prints

    "Driver not loaded Driver not loaded"
    

    I thought it was a problem with MySQL so I tried to connect to an SQLite database but to my surprise I got the same error message, meaning that there’s something wrong elsewhere.

    Since I’m on Debian, I thought I would try again using Qt from Debian’s repositories, so I installed all the missing development packages, added a Qt toolkit to QtCreator and tried again: same error.

    I know that the database is working because I also have a PyQt5 [again from Debian’s repositories] application that connects to a similar database by just

    db = QSqlDatabase.addDatabase("QMYSQL")
    db.setDatabaseName("SomeDatabase")
    

    and it works.

    What can I try next? Any clue is welcome.

  • I still think the sql plugin has some issues. Take a look what http://doc.qt.io/qt-5/qsqldatabase.html#drivers is telling you and make sure libqsqlmysql.so finds all it’s dependencies (e.g. with ldd)

  • Hi and welcome to devnet,

    To add to @Christian-Ehrlicher, this question has been asked many times already on this forum, please take the time to search through it.

  • Hi Christian, SGaist, thank you for your answers. As I mentioned in my post, I have already searched thoroughly the net for a solution, I have already re-compiled libqsqlmysql.so and calling ldd on it shows that not only does it not miss any dependency, it also links to the same libraries as the homonymous file from Debian’s repositories. In particular, it links to the installed version of libmariadbclient [Debian switched to MariaDB which is a fork of MySQL and a drop-in replacement].

    In any case, I also mentioned in my previous post that the problem is not specific to the MySQL driver, but I get the same error even if I try to use SQLite as a backend.

    What is the next thing that I can try?

  • Then start your application with the QT_DEBUG_PLUGINS environment variable set to 1. That will give you some more information about what is happening.

  • Thanks for the suggestion!
    This is the relevant output

    QFactoryLoader::QFactoryLoader() checking directory path "/opt/Qt/5.10.1/gcc_64/plugins/sqldrivers" ...
    QFactoryLoader::QFactoryLoader() looking at "/opt/Qt/5.10.1/gcc_64/plugins/sqldrivers/libqsqlite.so"
    Found metadata in lib /opt/Qt/5.10.1/gcc_64/plugins/sqldrivers/libqsqlite.so, metadata=
    {
        "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
        "MetaData": {
            "Keys": [
                "QSQLITE"
            ]
        },
        "className": "QSQLiteDriverPlugin",
        "debug": false,
        "version": 330241
    }
    
    
    Got keys from plugin meta data ("QSQLITE")
    QFactoryLoader::QFactoryLoader() looking at "/opt/Qt/5.10.1/gcc_64/plugins/sqldrivers/libqsqlmysql.so"
    Found metadata in lib /opt/Qt/5.10.1/gcc_64/plugins/sqldrivers/libqsqlmysql.so, metadata=
    {
        "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
        "MetaData": {
            "Keys": [
                "QMYSQL3",
                "QMYSQL"
            ]
        },
        "className": "QMYSQLDriverPlugin",
        "debug": false,
        "version": 330241
    }
    
    
    Got keys from plugin meta data ("QMYSQL3", "QMYSQL")
    
    
    loaded library "/opt/Qt/5.10.1/gcc_64/plugins/sqldrivers/libqsqlmysql.so"
    "Driver not loaded Driver not loaded"
    

    Meanwhile I have run the Qt example sqlbrowser and it does successfully connect to my MySQL local server, it shows me the database and the tables. This makes me suspect that there is an error in the code, but what could it be?

  • Debug VS Release version of the plugin ?

  • Sorry, I don’t understand the question :(
    Are you asking me to compare two different builds of the same plugin?

  • Did you build your plugin for both debug and release ?

  • need dynamic lib for mysql. For linux it’s libmysqlclient.so.16 or libmysqlclient.so.18 for your target platform.

  • @SGaist I built just one, with the default configuration. I will check which one when I get back to my home pc. What difference does it make? Could it work with one but not the other one?

    @Homer2000 I am using a shared library, except my distribution [like many others] now uses MariaDB as a replacement for MySQL, so I link to libmariadb.so or something similar

  • @Homer2000 No, by default the Qt MySQL plugin links against the MySQL client libraries.

    You can build it to use MariaDB though.

  • Ok, I found out what I was doing wrong.
    The code that I was using is

    QSqlDatabase db;
    db.addDatabase("QMYSQL");
    

    and it was giving me the error above, whereas the correct way to do it is

    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QMYSQL");
    

    and with this code it works fine.

    I don’t know why this is the case, I guess today I just learnt something new on Qt, thanks for the help everyboody!

  • @mleoni said in Cannot connect to databases, Driver not loaded error.:

    I don’t know why this is the case,

    Because QSqlDatabase::addDatabase() is a static function — no Qt magic here.

  • I see, so my mistake was letting the returned value go lost. Thanks for clarifying this!

  • Please take the time to read the QSqlDatabase documentation. It shows how to use it properly.

  • Thanks for the reference!

  • AlexandrBM

    0 / 0 / 0

    Регистрация: 28.01.2017

    Сообщений: 8

    1

    27.10.2018, 21:50. Показов 9625. Ответов 23

    Метки qt (Все метки)


    Здравствуйте. Столкнулся с проблемой, которую весь день не выходит решить. При попытке подключения к базе данных MYSQL выдает сообщение — driver not loaded. Весь интернет уже перерыл, mysql стоит 8.0 последняя, которую можно скачать с сайта. libmysql.dll уже скинул и в папку с исполняемым файлом и в папку bin компилятора (msvc2017_64). Использую последнюю стабильную версию qt 5.11.2 в связке с visual studio.
    Вот файлы, которые лежат в папке Debug —
    Вот что выводит при попытке подключения-
    Вот что прописано в PATH —
    Вот скриншоты из ODBC —

    C++ (Qt)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    #include <QCoreApplication>
    #include <QDebug>
    #include <QSqlDatabase>
    #include <QSqlError>
    #include <QSqlTableModel>
     
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QSqlDatabase main_db = QSqlDatabase::addDatabase("QMYSQL");
     
        main_db.setHostName("127.0.0.1");
        main_db.setUserName("root");
        main_db.setPassword("35345");
        main_db.setDatabaseName("mysql");
     
        if (!main_db.open())
        {
            qDebug() << main_db.lastError();
        }
        return a.exec();
    }

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    27.10.2018, 23:02

    2

    Отдельно от среды запускаешь? Библиотека от той же версии?



    0



    0 / 0 / 0

    Регистрация: 28.01.2017

    Сообщений: 8

    27.10.2018, 23:08

     [ТС]

    3

    Запускаю в Visual Studio, у меня стоит Qt VS tools плагин. В этот плагин указывается путь до компилятора.



    0



    0 / 0 / 0

    Регистрация: 28.01.2017

    Сообщений: 8

    28.10.2018, 20:03

     [ТС]

    4

    И еще тогда вопрос, обязательно ли самому компилировать плагин, если он уже доступен в среде?

    Добавлено через 1 час 32 минуты
    UPD: Скачал MySQL Connector C x64, скопировал оттуда libmysql.dll и поместил в папку, все заработало именно с этим dll файлом, другие не срабатывали.



    0



    2 / 2 / 0

    Регистрация: 22.11.2015

    Сообщений: 24

    01.11.2018, 13:34

    5

    AlexandrBM, день добрый! Столкнулся с такой же проблемой как у Вас.
    Стоит Windows 10 Pro x64.
    SQL Workbench 8.0.
    Qt 5.11.2.

    При попытке подключиться к базе данных SQL сообщение «driver not loaded».

    Скачал, как Вы писали, коннектор MySQL Connector C x64. Скопировал оттуда в папку с программой файл libmysql.dll. Не помогло.

    Пытался собрать плагин самостоятельно по документации. При выполнении следующей команды

    qmake — MYSQL_INCDIR=C:/MySQL/include «MYSQL_LIBDIR=C:/MYSQL/lib»

    выдаёт ошибку

    Cannot read C:/Qt/Qt5.11.2/5.11.2/Src/qtbase/src/plugins/sqldrivers/qtsqldrivers-config.pri: No such file or directory

    Что можно сделать? Если собирать плагин самому, то что с файлом qtsqldrivers-config.pri?
    Или как-то можно драйвер по другому подключить?



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    01.11.2018, 13:36

    6

    Там уже всё собрано. С libmysql.dll разберись — или версия не та, или помещаешь не в ту папку.



    0



    2 / 2 / 0

    Регистрация: 22.11.2015

    Сообщений: 24

    01.11.2018, 13:49

    7

    libmysql.dll качал версию 6.1.11. Помещать её надо в какую именно папку?



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    01.11.2018, 14:41

    8

    Рядом с exe попробуй.



    0



    2 / 2 / 0

    Регистрация: 22.11.2015

    Сообщений: 24

    02.11.2018, 06:58

    9

    Нет, не работает…



    0



    28 / 27 / 7

    Регистрация: 11.06.2011

    Сообщений: 387

    02.11.2018, 09:35

    10

    В разве нужен не sqldrivers/qsqlmysql.dll ?



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    02.11.2018, 09:42

    11

    Уже есть.



    0



    28 / 27 / 7

    Регистрация: 11.06.2011

    Сообщений: 387

    02.11.2018, 09:45

    12

    Надеюсь тоже с буквой d ?



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    02.11.2018, 10:45

    13

    Все есть.



    0



    28 / 27 / 7

    Регистрация: 11.06.2011

    Сообщений: 387

    02.11.2018, 10:48

    14

    А если запускать не из среды ?



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    02.11.2018, 10:58

    15

    Тогда надо копировать нужные библиотеки в соответствующие папки.



    0



    28 / 27 / 7

    Регистрация: 11.06.2011

    Сообщений: 387

    02.11.2018, 11:01

    16

    верно

    Добавлено через 2 минуты
    Может Qt 64bit, а libmysql.dll от 32bit ?



    1



    2 / 2 / 0

    Регистрация: 22.11.2015

    Сообщений: 24

    02.11.2018, 14:01

    17

    Всё! Проблема решена. Итог(для тех, кто столкнётся с этим потом):
    Windows 10 Pro
    SQL Workbench 8.0
    Qt 5.11.2 (от 18.09.2018)
    Скачан MySQL Connector/C версии 6.1.11 (Windows (x86, 32-bit), ZIP Archive).
    В этом архиве из папки lib был взят файл libmysql.dll и помещён в папку build-«название проекта».

    Заработало!
    Всем спасибо!

    Добавлено через 9 минут
    P.S. Если запускать сборку из Qt Creator, тогда достаточно нахождения libmysql.dll в папке build-«название проекта».
    Если запускать отдельно .exe, тогда надо класть libmysql.dll в папку к .exe



    0



    Lolobotik

    02.11.2018, 14:08

    Не по теме:

    Цитата
    Сообщение от Praid88
    Посмотреть сообщение

    Всё! Проблема решена

    В который раз :)

    Кликните здесь для просмотра всего текста

    Qt Mysql driver not loaded



    0



    2 / 2 / 0

    Регистрация: 22.11.2015

    Сообщений: 24

    02.11.2018, 14:38

    19

    Ну да))) Я согласен, что тема поднималась уже не однажды, просто версии Qt разные, версии Connector/С тоже разные. Например в Qt 5.2 там немножко по другому прописываются команды в командной строке и по сравнению с Qt 5.11 другие ошибки летят. И опять же, это только касательно SQL. А есть ещё другие драйвера. Тот же QIBASE, например. Я с ним тоже долго мучился. Просто в заголовках таких тем, на мой взгляд, надо сразу дописывать версии Qt и к какой базе данных пытаются подключится. Тогда сразу было бы видно.



    0



    7275 / 6220 / 2833

    Регистрация: 14.04.2014

    Сообщений: 26,871

    02.11.2018, 15:21

    20

    Praid88, и что ты делал не так?



    0



    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    02.11.2018, 15:21

    20


    How to solve » Driver not loaded »  error when connecting MySQL / MariaDB from a Qt application ?

    Note

    MariaDB database started as a fork of MySQL database, So most frameworks still uses MySQL connectors to connect to MariaDB.

    There are many reasons for this problem and they are the following.

    1. You are using MariaDB 10 or later.
    2. You need to add MySQL / MariaDB lib path to the path environment variables.
    3. Lake of QMYSQL driver or QMYSQL is found but incompatible with other libraries used in the application  (The same driver is used for both MySQL and MariaDB database servers).

    1- You are using MariaDB 10 or later.

    Starting from MariaDB 10 there is no libmysql.dll library in the lib folder of MariaDB, libmariadb.dll library is a replacement for libmysql.dll .

    • To solve this simply copy libmariadb.dll and rename the copy to libmysql.dll (do not rename the original libmariadb.dll this may prevent you from connecting to MariaDB using another application).

    2- You need to add MySQL / MariaDB lib path to the path environment variables.

    3- Lake of QMYSQL driver or QMYSQL is found but incompatible with other libraries used in the application  (The same driver is used for both MySQL and MariaDB database servers).

    In this case you need to build the driver to connect to MySQL / MariaDB.

    Here is the instructions to build QMySQL Driver on Gnu / Linux OS (Redhat / Centos / Fedora) .
    I have Fedora 28, MariaDB-10.2.16 and Qt 5.9.6
    After searching for long time I didn’t find any solutions, I decided to build the qt mysql driver although there was pre-built driver shipped with Qt 5 .
    It works after replacing the pre-built Qt MySQL driver with the one I’ve built.

    Instructions to build the mysql driver on Fedora / Redhat / Centos.

    For me I’ve Qt installed on the following path /opt/Qt5.9.6 so don’t forget to change the paths according to your installation.
    Also make sure that you have the package mariadb-devel or mysql-devel (this package includes header files used to compile the driver) installed according to the database server you have installed on your system, If they are not installed you can install it by the following command as super user

    
    dnf install mariadb-devel
    
    

    Building the Qt MySQL driver

    
    cd /opt/Qt5.9.6/5.9.6/Src/qtbase/src/plugins/sqldrivers/
    /opt/Qt5.9.6/5.9.6/gcc_64/bin/qmake -- MYSQL_PREFIX=/usr/include/mysql
    make sub-mysql
    
    

    After building the driver back the Qt pre-built libqsqlmysql.so up by the following command you may need it later.

    
    mv /opt/Qt5.9.6/5.9.6/gcc_64/plugins/sqldrivers/libqsqlmysql.so /opt/Qt5.9.6/5.9.6/gcc_64/plugins/sqldrivers/libqsqlmysql.so.old 
    
    

    And the final step is copy our mysql driver to Qt plugin folder by the following command.

    
    cp /opt/Qt5.9.6/5.9.6/Src/qtbase/src/plugins/sqldrivers/plugins/sqldrivers/libqsqlmysql.so /opt/Qt5.9.6/5.9.6/gcc_64/plugins/sqldrivers/
    
    

    Now run your application and connect to mariadb (MySql).
    Also I’ve the same issue on windows I’ll try to build the driver on windows and I’ll add the instructions later.

    Дано
    ОС 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:Qt5.5.1mingw491_32binpluginssqldrivers) и копируем в подкаталог 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)PostgreSQL10bin). Здесь есть две важнейшие особенности:

    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 примером на гуглодиске

    After spending a quite a bit of time to find the solution of this often-occurring
    QMYSQL driver not loaded problem mainly after installing Qt installation in a new software environment, So I thought I am going to share my best practice to fix this issue.
    I wasn’t able to establish database connection even if I received the list of available drivers:

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

    The following simple method helps to fix the problem.
    On OSX system just simple install or re-install mysql using the flowing command. I usually prefer Homebrew as it fulfils most my requirements and using MacPort when I really no other options available.

    $ brew install mysql

    then place the following
    libmysqlclient.18.dylib.zip (719 downloads)

    file to the path below:

    /opt/local/lib/mysql55/mysql/
    /opt/local/lib/mysql55/mysql/libmysqlclient.18.dylib

    On different Linux distributions I usually apt install or yum install the MySQL package basically the only thing I need to make sure that place the
    libmysqlclient.18.dylib.zip (719 downloads)

    file to the following path:

    /opt/local/lib/mysql55/mysql/

    This method solves the QMYSQL driver not loaded issue and allows me to establish database connection, it might work on Windows system as well, however I had not opportunity to try before.
    Please, let me know if this method also working for you by dropping a line.

    Download:
    libmysqlclient.18.dylib.zip (719 downloads)

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Dawn of war error 183
  • Dawn of war 2 не запускается error report
  • Dawn of war 2 error report при запуске
  • Davinci resolve ошибка при рендере
  • Database error connection failed unable to connect to the database please contact your server administrator

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии