Connect to an MySQL Database via Python

How to connect your Python Notebook to MySQL Databases

Christianlauer
CodeX

--

Photo by Rafael Hoyos Weht on Unsplash

Often, data scientists or analysts have to access databases for example for ad-hoc analysis. Often, these are MySQL databases, here you can use the MySQL Connector to access a MySQL database from a Jupyter notebook.

First step is to install the connector via !pip install command:

!pip install mysql-connector-python

After that you can already use the library and connect to the database:

#Import the Connector
import mysql.connector
# Connecting to the database
conn = mysql.connector.connect(user = ‘username’,host = ‘localhost’,database = ‘database_name’)

And with the help of a cursor object you can then query tables:

# Initialize a Cursor Object
cursorObject = dataBase.cursor()
# Select Query
query = "SELECT NAME, FORNAME FROM CUSTOMER"
cursorObject.execute(query)
result = cursorObject.fetchall()

From here on, you can use the result for data preparation and aggregation. Last but not least — always disconnect from the server when done:

# Disconnect from Server
conn.close()

--

--

Christianlauer
CodeX
Editor for

Big Data Enthusiast based in Hamburg and Kiel. Thankful if you would support my writing via: https://christianlauer90.medium.com/membership