PyMySQL连接到远程数据库

时间:2017-08-28 11:14:20

标签: python mysql pymysql

我正在学习Python并尝试连接到远程数据库的教程。 我遇到的问题是我不知道用什么替换localhost,我已经尝试了域名,IP地址等但是不断收到以下错误。

  

OperationalError:(2003,“无法连接到'remotehost上的MySQL服务器   名字'(超时)“)

# Open database connection
db = pymysql.connect("localhost","username","password","dbname" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS rsstracker")

# Create table as per requirement
sql = """CREATE TABLE rsstracker (
   article_title  varchar(255),
   article_url  varchar(1000),
   article_summary varchar(1000)
   summary )"""

cursor.execute(sql)

# disconnect from server
db.close()

1 个答案:

答案 0 :(得分:1)

您应该将localhost替换为服务器的IP地址或主机名。如果该服务器在您的LAN中,您将需要其内部地址。如果它在您的网络之外,您将需要其外部地址。

无论哪种方式,您都需要确保您正在使用的端口转发良好,并且不会被路由器/防火墙阻止/过滤,包括在远程服务器的操作系统上/通过远程服务器的操作系统。

这个问题可能更合适superuser exchange