我在将Amazon AWS MySQL与SQLAlchemy连接时遇到问题。根据指示,我已连接。
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://<user>:<password>@<host>/<dbname>
但是有一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 514, in __get__
return type.query_class(mapper, session=self.sa.session())
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 74, in __call__
return self.registry()
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2950, in __call__
return self.class_(**local_kw)
File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 143, in __init__
bind = options.pop('bind', None) or db.engine
File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 877, in engine
return self.get_engine()
File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 896, in get_engine
return connector.get_engine()
File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 559, in get_engine
self._engine = rv = sqlalchemy.create_engine(info, **options)
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 81, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 102, in dbapi
return __import__('MySQLdb')
ModuleNotFoundError: No module named 'MySQLdb'
我正在使用Python3.7版本。即使根据stackoverflow,我已经安装了pymysql,但是仍然面临问题。
谢谢您的答复。
答案 0 :(得分:1)
如果您使用PyMySQL客户端连接到MySQL,则您的SQLAlchemy连接字符串必须以
开头 mysql+pymysql://
代替mysql://
。
如果使用mysql://
连接,则需要安装MySQLdb库,如回溯所示。
答案 1 :(得分:1)
第1步 如果要使用MySQLDB,则需要使用以下命令之一。哪一个取决于您拥有和使用的操作系统和软件。
easy_install mysql-python
(混合操作系统)
pip install mysql-python
(mix os / python 2)
pip install mysqlclient
(mix os / python 3)
apt-get install python-mysqldb
(Linux Ubuntu,...)
cd /usr/ports/databases/py-MySQLdb && make install clean
(FreeBSD)
yum install MySQL-python
(Linux Fedora,CentOS ...)
对于Windows,请参见以下答案:Install mysql-python (Windows)
第2步:
engine = create_engine('mysql+mysqldb://...', pool_recycle=3600)
使用create_engine.pool_recycle
选项,以确保连接在池中存在固定的秒数后将被丢弃并替换为新的连接:
conn = engine.connect()
conn.execute("SELECT * From table;")
答案 2 :(得分:0)
上述问题已通过以下解决:
import pymysql
pymysql.install_as_MySQLdb()
什么都没改变