Search code examples
pythonmysql-connector-python

How to connect to MySQL over `TCP/IP` and `TCP/IP over ssh` from python code?


I am able to connect to my database with sql workbench. But when I am trying to connect with python code, I am getting confused. I have found some similar codes on internet and stack over flow but I am not able to connect with code.

How can I connect to the DB with the following details? Using python code.

mySQL workbench connection

EDIT:: I also want to know how to connect to TCP/IP over ssh. details shown in below image.

enter image description here


Solution

  • You can use the python-mysql driver

    import mysql.connector
    
    mydb = mysql.connector.connect(
      host="localhost",
      port="2121",
      user="yourusername",
      password="yourpassword"
    )
    
    print(mydb)
    

    This doc explains it in details.

    Connecting VIA SSH is descibed here - Enable Python to Connect to MySQL via SSH Tunnelling