How to connect to MySQL server on another host?
Django can simply connect to its own MySQL server by setting HOST
and PORT
in settings.py
as '' (empty string):
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.
}
}
My question is how to make it able to connect another database on another host? Suppose my machine is 192.168.1.33
and another machine to be connected is 192.168.1.34
, both are on the same network. I've tried to set this as:
'HOST': '192.168.1.34',
'PORT': '3306',
and
'HOST': '192.168.1.34',
'PORT': '',
but both caused this OperationalError
:
(2003, "Can't connect to MySQL server on '192.168.1.34'(10061)")
SOLUTION: credit @cdhowie
Config bind-address to the host you want in
/etc/mysql/my.cnf
Create a new user for the host you want to give an access (if you don't have one).
Check privileges for that user (if access denied).
By default, Debian-based distros configure MySQL to bind to localhost only, which means that other hosts cannot connect to it. Fix your MySQL configuration and it will work.
Edit /etc/mysql/my.cnf
and change this line:
bind-address = 127.0.0.1
To this:
bind-address = 0.0.0.0
This will expose MySQL to all network interfaces, so make sure that you have security measures in place if this server is exposed to untrusted hosts.
精彩评论