Django可以通过在settings.py
中将HOST
和PORT
设置为空字符串,来简单地连接到自己的MySQL服务器:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dbname', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'root', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
我的问题是如何使它能够连接到另一个主机上的另一个数据库?假设我的计算机是192.168.1.33
,要连接的另一台计算机是192.168.1.34
,两者都在同一个网络上。我尝试将其设置为:
'HOST': '192.168.1.34',
'PORT': '3306',
并且
'HOST': '192.168.1.34',
'PORT': '',
但是这两者都会导致
OperationalError
的出现:(2003, "Can't connect to MySQL server on '192.168.1.34'(10061)")
解决方案:感谢 @cdhowie
在
/etc/mysql/my.cnf
中配置 bind-address 为您想要的主机。为您想要授予权限的主机创建新用户(如果没有)。
检查该用户的权限(如果访问被拒绝)。