2

我想将 SQLAlchemy 与 MySQL 数据库一起使用。我已经创建了引擎并尝试连接,但出现如下错误。

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Engine = create_engine('mysql+mysqldb://dbuser:pass@localhost/mydb')
Base = declarative_base(Engine)

失败并出现错误:

File "/usr/local/lib/python3.2/dist-packages/SQLAlchemy-0.8.0b2-py3.2.egg/sqlalchemy/connectors/mysqldb.py", line 57, in dbapi
return __import__('MySQLdb')
ImportError: No module named MySQLdb

搜索我发现你必须为 python 安装 MySQLdb 才能很好地使用 MySQL。因此,尝试使用pip-3.2 或 easy_install-3.2安装它会失败,如下所示。

sudo pip-3.2 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call last):
  File "<string>", line 16, in <module>
  File "/tmp/pip-build/MySQL-python/setup.py", line 14, in <module>
    from setup_posix import get_config
  File "setup_posix.py", line 2, in <module>
    from ConfigParser import SafeConfigParser
ImportError: No module named ConfigParser
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/tmp/pip-build/MySQL-python/setup.py", line 14, in <module>
from setup_posix import get_config
 File "setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ImportError: No module named ConfigParser

然后我想我必须安装configparser所以当我尝试这样做时它也会失败

Original exception was:
Traceback (most recent call last):
 File "<string>", line 3, in <module>
 File "/usr/local/lib/python3.2/dist-packages/distribute-0.6.34-py3.2.egg/setuptools/__init__.py", line 2, in <module>
from setuptools.extension import Extension, Library
File "/usr/local/lib/python3.2/dist-packages/distribute-0.6.34-py3.2.egg/setuptools/extension.py", line 2, in <module>
import distutils.core
File "/usr/lib/python3.2/distutils/core.py", line 19, in <module>
from distutils.config import PyPIRCCommand
File "/usr/lib/python3.2/distutils/config.py", line 8, in <module>
from configparser import ConfigParser
 File "configparser.py", line 122

所以,我最初的问题是试图让 Python 与 MySQL 一起工作。但试图解决我无法安装 MySQLdb 的问题。

编辑 按照下面@robertklep 的指示继续并安装pymsql3。

sudo pip-3.2 install pymysql3

问候,

4

2 回答 2

6

MySQLdb 不支持 Python 3。尝试一个替代方案,比如PyMySQLSQLAlchemy 也支持)。

编辑:还有这个项目

于 2013-03-01T08:25:11.083 回答
3

https://www.pythonanywhere.com/wiki/UsingMySQL

pip install --user https://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-1.1.6.tar.gz

然后,更新您的 settings.py 以使用 oracle django 后端“mysql.connector.django”:

DATABASES = {
    'default': {
        'ENGINE': 'mysql.connector.django',
         ...
于 2014-04-29T09:30:29.627 回答