gpt4 book ai didi

python - [django+mysql]MySQLdb.connect工作正常,但无法通过settings.py连接mysql

转载 作者:行者123 更新时间:2023-11-29 12:33:49 25 4
gpt4 key购买 nike

我正在尝试用 django 连接 mysql。以下命令可以正常工作。

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 32位,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)")

最佳答案

数据库的设置应该是HOSTPORT,而不是DATABASE_HOST ...所以试试这个:

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

关于python - [django+mysql]MySQLdb.connect工作正常,但无法通过settings.py连接mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27089461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com