1
import mysql.connector

db = mysql.connector.connect(
    host = "",
    user = "username",
    passwd = "password",
    database = "theDatabase")

c = db.cursor()

c.execute("SELECT * FROM Test2")
print(c.fetchall())

Hi, using this piece of code I can connect to my mysql database that is another computer on the same network. But if I wanted to connect to the database from a computer that is not on the same network, how would I do that? Thanks for all/any responses.

VijayS
  • 11
  • 3
  • This code won't connect to another computer. You need to put the name or address of the database server in the `host =` argument. – Barmar Dec 30 '19 at 22:43
  • It works the same whether the computer is in the same or a different network. – Barmar Dec 30 '19 at 22:43
  • However, if there's a firewall protecting the other network, you'll need to allow the MySQL port through to the server. It's port 3306. – Barmar Dec 30 '19 at 22:44

2 Answers2

1

If host is empty "" it will connect tot 127.0.0.1 (localhost). This is fine if your database is on the same server as your webpage or application (which is almost never the case).

Referring to this URL, valid parameters for the host are an IP address. Add the ip of the server where your database runs. Maybe you need to add some firewall rules to allow the connection.

Above is my best guess but i am sure there are some people that can help you better.

Achuja
  • 11
  • 1
0

The mysql server have to be publicly available from outside on port 3306. If you want to connect from outside it depends on your network. Normally you have to NAT the port to the internal machine that it's available from outside.

https://stevessmarthomeguide.com/understanding-port-forwarding/

If it's available on the IP on port 3306 you can connect to it. It's the same like connecting from inside. Connect directly to the ip.

You can check if the connection works with telnet for example.

telnet 1.1.1.1 3306

It is possible that you have to change your mysql user that the user accessible from * and not from localhost or your network only. That depends how you have configured your user.

How to grant remote access permissions to mysql server for user?

René Höhle
  • 26,716
  • 22
  • 73
  • 82