pyqt5 QMYSQL driver not loaded

# -*- coding: utf-8 -*-
import sys  
from PyQt5 import QtSql
if __name__ == '__main__':
    db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
    db.setHostName("localhost")
    db.setDatabaseName("mysql")
    db.setUserName("root")
    db.setPassword("root")
    db.setPort(3306)
    db.open()

错误:

QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7
QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins

解决方案:

# -*- coding: utf-8 -*-
import sys  
from PyQt5 import QtSql
import ctypes
if __name__ == '__main__':
    ctypes.windll.LoadLibrary('D:/Program Files/mysql-advanced-5.6.23-winx64/lib/libmysql.dll')
    db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
    db.setHostName("localhost")
    db.setDatabaseName("mysql")
    db.setUserName("root")
    db.setPassword("root")
    db.setPort(3306)
    print(db.open())

根本原因是qt用的是c++的库,加载不到驱动。用python 加载dll 让python 在上下文中能读取到驱动
ctypes.windll.LoadLibrary(‘D:/Program Files/mysql-advanced-5.6.23-winx64/lib/libmysql.dll’)

你可能感兴趣的:(python,pyqt)