折腾到爆炸了!暂时只能把PyQt5版本降到 5.12.2 使用 (所包含的QT版本是5.12.3)
QT链接MYSQL需要两个桥梁:qsqlmysql.dll、 libmysql.dll (前者是驱动,后者是扩展包[接口库])
但PyQt中这两个文件都没有提供。关于这点,官方有说明:https://doc.qt.io/qt-5/sql-driver.html#qmysql (由于版权的关系在5.12版后就不再提供MySQL驱动程序,所以用户需要自己编译)
百度、google试了各种方法,最常见的方案是:
1、安装QT(安装的这个QT的版本 与 PyQt、PySide2中的那个QT的版本 要相同)
2、对QT提供mysql.pro源文件进行编译,得到驱动dll
视频教程:(哔哩哔哩搜索关键词: 'QT MYSQL')
https://www.bilibili.com/video/BV1Jk4y167tt ([QT 5.14.2]【经验分享】Qt连接Mysql)
https://www.bilibili.com/video/BV17z411z7T2 (QT5.12.9连接MySQL8.0开发示例)
详细讲解:
https://stackoverflow.com/questions/64056483/unable-to-load-qmysql-driver-on-pyside2
而最简单直接的方法是:
1、检查自己的QT版本,然后百度别人针对这个版本编译好的现成驱动,下载。
【传送门:https://github.com/thecodemonkey86/qt_mysql_driver/releases (很多版本都有)】
2、把找来的两个文件粘帖到对应目录。
//版本获取方式:
//PyQt5
python -c "from PyQt5.QtCore import QT_VERSION_STR; print('Qt version', QT_VERSION_STR)"
//PySide2
python -c "from PySide2.QtCore import qVersion; print('Qt version', qVersion())"
//目录获取方式:
//PyQt5:
python -c "import os; from PyQt5.QtCore import QLibraryInfo; print('QT_SQL_DRIVER_PATH', os.path.join(QLibraryInfo.location(QLibraryInfo.PrefixPath), 'plugins', 'sqldrivers'))"
//PySide2:
python -c "import os; from PySide2.QtCore import QLibraryInfo; print('QT_SQL_DRIVER_PATH', os.path.join(QLibraryInfo.location(QLibraryInfo.PrefixPath), 'plugins', 'sqldrivers'))"
有我不想安装QT,又百度不到现成的5.15.2,所以尝试了降版本的方式:
1、卸载现有版本,安装有提供 qsqlmysql.dll 的最后一个PyQt5版本 5.12.2
pip uninstall PyQt5
pip install PyQt5==5.12.2
2、把mySql5.7的 libmysql.dll、libmysql.lib 拷贝到 site-packages\PyQt5\Qt\bin 中
3、安装这个版本后发现运行提示:
from PyQt5.QtSql import QSqlDatabase
ImportError: DLL load failed while importing QtSql: 找不到指定的模块。
pycharm中代码就红色波浪线提示:
Cannot find reference 'QtCore' in '__init__.py | __init__.py'
折腾一轮后,解决办法是:把高版本的init__.py 中的内容复制粘帖到低版本的init__.py中 (就是以下这段,其中第7行的'\\Qt5\\bin' 改为 '\\Qt\\bin')
def find_qt():
import os, sys
qtcore_dll = '\\Qt5Core.dll'
dll_dir = os.path.dirname(sys.executable)
if not os.path.isfile(dll_dir + qtcore_dll):
path = os.environ['PATH']
dll_dir = os.path.dirname(__file__) + '\\Qt\\bin'
if os.path.isfile(dll_dir + qtcore_dll):
path = dll_dir + ';' + path
os.environ['PATH'] = path
else:
for dll_dir in path.split(';'):
if os.path.isfile(dll_dir + qtcore_dll):
break
else:
return
try:
os.add_dll_directory(dll_dir)
except AttributeError:
pass
find_qt()
del find_qt
运行成功。
还有一个方案是使用ODBC,在odbc设置中加入mysql。设置方法参考请百度
-------
其他:
期间遇到过的其他一些坑:
1、把5.12.2 的qsqlmysql.dll 拷贝到 5.15.2 中,用官网下载的 libmysql.dll ,没有提示 Driver not loaded 了,但执行结果是 Process finished 1073740791 (0xC0000409) 。--->折腾了一轮,无解!
参考:
https://blog.csdn.net/m15814478834/article/details/49902077 QMYSQL driver not loaded 的原理和解决办法
https://blog.csdn.net/qq_34769196/article/details/103898208 PyQt5使用QSqlDatabase类连接Mysql的坑:QMYSQL driver not loaded
gitub上找到现成可以下载的驱动(各版本):
https://github.com/thecodemonkey86/qt_mysql_driver/releases
其中我下载了5.15.2版本