To connect MySQL using Python, follow the steps below:
Step 1: Install Python MySQL Connector
In order to connect to MySQL using Python, we need to first install the required driver. In this tutorial,we are going to use mysql-connector-python package.
To install the package, run the following command.
Step 2: Installing MySQL and creating Database
This is an optional step. If you already have MySQL installed, skip to the next step. Follow this tutorial to install MySQL in the Mac operating system.
Once MySQL is installed, run the following command to connect to MySQL.
You can use your own username in the place of root.
Run this command in the MySQL shell to create a new database.
Replace database_name with your own database.
Run this command to create a new table.
Add some data to the table.
Step 3: Connecting MySQL using Python
Copy-paste the code shown below to your editor and save it as app.py.
mydb = mysql.connector.connect(
cursor = mydb.cursor()
cursor.execute("SELECT * from users")
result = cursor.fetchall()
for row in result:
Replace the database_name with your own database name.
Run the program using the following command.
You should be getting the output as data from your MySQL table.
This tutorial is a part of the free course – learn python from scratch. Enroll in this free course to learn Python from scratch.