Home > Net >  How do I connect to a MySQL Database in Python with a RaspberryPi
How do I connect to a MySQL Database in Python with a RaspberryPi

Time:02-16

I'm a student and I'm trying to write some sensor values into a MySQL database.

As IDE I'll be using Inteliji. First off I started by installing the database Plug-in.

  • This was done successfully

Next I tried to connect to the data base (see figure below)

Figure of successful connection

Now The next thing I want to do is use a MySQL connector. Therefore I've installed MySQL onto the r-PI and used following code to implement it.

import mysql.connector
print("Step 1")
cnx = mysql.connector.connect(user='a21ib2a01', 
                              password='secret',
                              host='mysql.studev.groept.be',
                              database='a21ib2a01')
Print("Step 2")

When now I run my code the terminal will output:

Step1

For some reason I don't know; the connect function always times my program out with the next occurring errors:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'mysql.studev.groept.be:3306' (110 Connection timed out)

So does anyone know why my connection is successful but I can't connect to it? Long story short what am I doing wrong and how do I fix this?

Thanks in advance!

CodePudding user response:

Your timeout means the network on your rPi cannot reach -- cannot find a route to -- your MySQL host mysql.studev.groept.be.

If you do traceroute mysql.studev.groept.be in a shell in the rPi you may see what's wrong.

When in a shell on your rPi, can you ssh to any machine in your uni's network? If so, you might be able to use ssh port-forwarding to get a route to the database server.

Do you run intelliJ on the rPi directly, or on your laptop? If you run it on the laptop, it looks like the laptop can find a route to your server but the rPi cannot.

(If this were my project, I'd install a MySQL server on my laptop to reduce the network-engineering hassles of connecting through multiple hops involving a VPN.)

  • Related