简体   繁体   English

如何使用python通过IP地址连接mysql?

[英]How to use python to connect mysql via ip address?

I want to try to use python to connect to MySQL database. 我想尝试使用python连接到MySQL数据库。

Connecting to localhost works fine but I can not connect to MySQL database via ip address. 连接到本地主机工作正常,但我无法通过IP地址连接到MySQL数据库。

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)") OperationalError:(2003年,“无法连接到“我的电脑IP”上的MySQL服务器(111)”)

I found that someone who also has asked the similar question on stackoverflow --> Can't connect to MySQL server error 111 我发现有人也对stackoverflow提出了类似的问题-> 无法连接到MySQL服务器错误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. 我最初在文档“ my.cnf”中没有行跳过网络。

So basically, mysql should not listen only 127.0.0.1. 因此,基本上,mysql不应该仅侦听127.0.0.1。 In theory, mysql can listen any IP and I also set the port 3306 to be allowed in my computer. 从理论上讲,mysql可以侦听任何IP,并且我还将计算机中允许的端口3306设置为允许。

Does anyone has some suggestion? 有人有什么建议吗?

This answer works for me: Trying to connect to remote MySQL host (error 2003) 这个答案对我有用尝试连接到远程MySQL主机(错误2003)

I got the same error, when I connected db using localhost , connection was OK. 当我使用localhost连接数据库时,出现了同样的错误,连接正常。 But using ip 114.***.***.*** , from another pc, or from the db server itself, were all failed. 但是从另一台PC或数据库服务器本身使用ip 114.***.***.***都失败了。 And I can ping this ip from another pc. 而且我可以从另一台PC ping此IP。

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. 我的错误是由中间路由器引起的,当我想通过ip(不是localhost127.0.0.1 )访问数据库时,连接请求已发送到路由器,然后转发到数据库服务器。 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. 因此,我在路由器的“配置”页面上为其添加了一条规则,然后成功连接了数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM