Forums

ssh connection for pandas read sql

I can connect to mySQL on PA with ssh, but I'd like to read the sql directly as a pandas dataframe, using:

df = pd.read_sql('SELECT * FROM mytable', connection)

Could you help with syntax for the ssh in the connection above. The error line is: port=tunnel.local_bind_port and traceback message is that server is not started.

Here is my failed attempt. thanks,

import pandas as pd
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

user='username'
password='password_for_database'
host='127.0.0.1'
port=tunnel.local_bind_port
database='username$tutorial'

with sshtunnel.SSHTunnelForwarder(
                ('ssh.pythonanywhere.com'),
                ssh_username='username', ssh_password='password_for_PA!',
                remote_bind_address=('username.mysql.pythonanywhere-services.com', 3306)
            ) as tunnel:
                           connection = mysql.connector.connect(user, password, host, port, database)

df = pd.read_sql('SELECT * FROM my_table', connection)        
df

I would think that would work. What happens?

The error line is: port=tunnel.local_bind_port and traceback message is that server is not started.

Looking at your code, it appears that you're trying to access the variable tunnel before it's been initialised. Try moving the

port=tunnel.local_bind_port

...inside the with block.