Python 3.* 使用 sqlalchemy 模块报错‘ModuleNotFoundError: No module named ‘MySQLdb
Traceback (most recent call last):
File "sqlalchemy_select.py", line 24, in <module>
engine = create_engine('mysql://******:******@192.***.31.***/zst?charset=utf8mb4')
File "/root/.pyenv/versions/3.8.6/lib/python3.8/site-packages/sqlalchemy/engine/__init__.py", line 500, in create_engine
return strategy.create(*args, **kwargs)
File "/root/.pyenv/versions/3.8.6/lib/python3.8/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "/root/.pyenv/versions/3.8.6/lib/python3.8/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 118, in dbapi
return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'
对于刚接触 sqlalchemy 这个模块的我来说,该报错着实让我有点摸不着头脑╮(╯▽╰)╭
但 Traceback 大兄弟还是给出了些线索:File "/root/.pyenv/versions/3.8.6/lib/python3.8/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 118, in dbapi \n return __import__("MySQLdb")
- 可以看到是 ‘mysqldb.py’ 这个文件犯病了,在这里需要调用一下 MySQLdb 模块,所以会出现上面的报错
@classmethod
def dbapi(cls):
return __import__("MySQLdb")
原因如下
- 在 python2 中,使用 pip install mysql-python 进行安装连接MySQL的库,使用时 import MySQLdb 进行使用;
- 而在 python3 中,连接库改为了 pymysql 库。
解决办法
- 找到该文件同级目录下的 __init__.py 文件,添加如下两行即可
import pymysql
pymysql.install_as_MySQLdb()
- 完成之后再运行之前犯病的脚本(纵享新丝滑)
#python sqlalchemy_select.py
count:‘.filter(Activity.hold_time.like('2020-11-20 23:12:02')).count()’
10
使用参数:‘.filter(text("id > :value")).params(value=2).all()’
直接使用 SQL:‘.from_statement(text("select * from t_activity"))’
<Activity(id=1, name=rPUBvFTX, time=2020-11-20 23:12:02, form=rPUBvFTX)>
<Activity(id=2, name=q0nSxZuw, time=2020-11-20 23:12:02, form=q0nSxZuw)>
<Activity(id=3, name=v4bpusGH, time=2020-11-20 23:12:02, form=v4bpusGH)>
<Activity(id=4, name=UGNptofQ, time=2020-11-20 23:12:02, form=UGNptofQ)>
<Activity(id=5, name=qjWvkdoC, time=2020-11-20 23:12:02, form=qjWvkdoC)>
<Activity(id=6, name=jQm9yTz7, time=2020-11-20 23:12:02, form=jQm9yTz7)>
<Activity(id=7, name=05nqWELM, time=2020-11-20 23:12:02, form=05nqWELM)>
<Activity(id=8, name=nHBVpq9F, time=2020-11-20 23:12:02, form=nHBVpq9F)>
<Activity(id=9, name=8uHcRmLB, time=2020-11-20 23:12:02, form=8uHcRmLB)>
<Activity(id=10, name=WRPg3b7Z, time=2020-11-20 23:12:02, form=WRPg3b7Z)>
<Activity(id=11, name=a, time=2020-11-20 23:32:08, form=线下)>
本文地址:https://blog.csdn.net/BDR_dyf/article/details/109883773