0

I want to try to use python to connect to MySQL database.

Connecting to localhost works fine but I can not connect to MySQL database via ip address.

Here is my code:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import MySQLdb


db = MySQLdb.connect(host="My Computer IP",
    user="root", passwd="606", db="testdb",port=3306)
cursor = db.cursor()


cursor.execute("SELECT * FROM table1")


results = cursor.fetchall()


for record in results:
  col1 = record[0]
  col2 = record[1]
  print "%s, %s" % (col1, col2)


db.close()

The error is like this:

OperationalError: (2003, "Can't connect to MySQL server on 'My Computer IP' (111)")

I found that someone who also has asked the similar question on stackoverflow --> Can't connect to MySQL server error 111

I have tried this method but it still doesn't work.

I don't have the line skip-networking in the document "my.cnf" originally.

So basically, mysql should not listen only 127.0.0.1. In theory, mysql can listen any IP and I also set the port 3306 to be allowed in my computer.

Does anyone has some suggestion?

matino
  • 17,199
  • 8
  • 49
  • 58
陳俊良
  • 319
  • 1
  • 6
  • 13

1 Answers1

0

This answer works for me: Trying to connect to remote MySQL host (error 2003)

I got the same error, when I connected db using localhost, connection was OK. But using ip 114.***.***.***, from another pc, or from the db server itself, were all failed. And I can ping this ip from another pc.

My error was caused by an intermediate router, when I wanted to access the db via ip (not localhost or 127.0.0.1), the connection request was sent to the router, then forwarded to the db server. And the router didn't have forwarding rules about that.

So I added a rule to the router by its config page, then connected the db successfully.

Denny
  • 137
  • 1
  • 6