
How to connect Python with mysql container:
This article is a continuation of the mysql docker container series. Therefore, in this article we shall focus on the process of connecting mysql docker container with Python.
We shall keep this article technically simple, we shall define a Python class that will have database connection and we shall try to fetch some data. You can think this article is a building block to create more complex Python related project where multiple technology are working together.
What the Python code will do :
We shall define a Python class, that will have a init method and one member function. The init method will connect to the mysql database inside the docker container using proper credential which we have configured during our mysql container setup.
The member function will have resposibility to fetch the customer information given the id.
The Python Code :
import mysql.connector class SakilaConnection: def __init__(self): self.connectionString = mysql.connector.connect(host="192.168.1.201",user="dev1",password="dev1",database="sakila") self.cursor = self.connectionString.cursor() def getCustomerInfo(self,customerID): queryString = f"select * from customer where customer_id = {customerID}" self.cursor.execute(queryString) myresult = self.cursor.fetchall() return myresult[0] customer1 = SakilaConnection() result = customer1.getCustomerInfo(16) print(result[2])
Things to remember:
- Make sure the container configured properly as per the Youtube video.
- Container should have the data, inother words it should have the tables.
- Be sure the container is in the running state.
Conclusion:
In this article we have connected python code with mysql contianers. Now upto you to download any database of your choice but the configuration steps remains almost the same.