Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - 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

  1. Config bind-address to the host you want in /etc/mysql/my.cnf

  2. Create a new user for the host you want to give an access (if you don't have one).

  3. Check privileges for that user (if access denied).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...