[django + mysql] MySQLdb.connect运行良好,但无法通过settings.py连接mysql

时间:2014-11-23 13:29:21

标签: python mysql django

我试图将mysql与django连接起来。以下命令可以很好地工作。

import MySQLdb
>>> con = MySQLdb.Connect(host = "127.0.0.1", port= 3306, user = "root", passwd = "mycode", db = "test")
>>> con.cursor()
<MySQLdb.cursors.Cursor object at 0x020F2230>
>>> cursor = con.cursor()
>>> sql = "SELECT * FROM test.testing"
>>> cursor.execute(sql)
0L

当我尝试通过settings.py连接数据库时,它崩溃了,我找不到任何关于它的线索。这是我在settings.py中的配置

DATABASES = {
    'default':{
        'ENGINE' : 'django.db.backends.mysql',
        'NAME' : 'tasty',
        'USER' : 'root',
        'PASSWORD' : 'mycode',
        'DATABASE_HOST' : '127.0.0.1',
        'DATABASE_PORT' : '3306',
    },
}

我从命令行得到的错误信息如下。我怀疑我得到错误的原因,是django无法为数据库连接获取正确的参数。我的环境是win7 32bit,python 2.7.5,django 1.6.7 ,mysql 5.1,MySQL-python-1.2.4b4.win32-py2.7。请有人帮助我,任何建议都会受到欢迎。

>>> from django.db import connection
>>> cursor = connection.cursor()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 160,
 in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 132,
 in _cursor
    self.ensure_connection()
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 127,
 in ensure_connection
    self.connect()
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 99, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 127,
 in ensure_connection
    self.connect()
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 115,
 in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 43
5, in get_new_connection
    conn = Database.connect(**conn_params)
  File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __in
it__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

1 个答案:

答案 0 :(得分:1)

数据库的设置应为HOSTPORT,而不是DATABASE_HOST ...请尝试以下操作:

DATABASES = {
    'default':{
        'ENGINE' : 'django.db.backends.mysql',
        'NAME' : 'tasty',
        'USER' : 'root',
        'PASSWORD' : 'mycode',
        'HOST' : '127.0.0.1',
        'PORT' : '3306',
    },
}