Search code examples
pythonmysqlpymysql

PyMySQL Connecting to a Remote Database


I'm learning Python and attempting a tutorial to connect to a remote database. The problem that I'm having is that I'm not sure what to replace localhost with, I've tried domains, IP address etc. but keep getting the following error.

OperationalError: (2003, "Can't connect to MySQL server on 'remotehost name' (timed out)")

# 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()

Solution

  • You should replace localhost with the server's IP address or host name. If that server is in your LAN you will need its internal address. If it is outside your network you will need its external address.

    Either way you will need to make sure the port you are using is well forwarded and not blocked/filtered by routers / firewalls along the way, including on / by the remote server's operating system.

    This question may be more appropriate on superuser exchange.