In this tutorial, you will all about How to connect Python to MySQL database. If you want to use your Python application with MySQL database, then you have to connect your application with the MySQL database.
In this guide, we will see step by step guide to connecting Python application with MySQL database.
To connect Python to MySQL database, You should have MySQL installed in your machine or computer system.
You can download MySQL from click here.
Install MySQL Driver
After download and install the MySQL database on your machine, you should have download the MySQL driver.
MySQL driver works with the connector to connect your Python application with the MySQL database.
You can use the python pip command to download the MySQL driver.
Use the following command to download the MySQL driver.
pip install mysql-connector-python
After executing above command, MySQL driver will download and install in your system.
Connect Python to MySQL
To connect Python to MySQL, you have to import the MySQL connector in your python file using the import keyword.
We have a python file named connect_mysql.py that contains codes related to database connection.
import mysql.connector print('successful')
If you get ‘successful‘ message after executing above python file, then MySQL driver successfully installed in your machine.
Now you are able to connect your Python file with the MySQL database.
To connect with MySQL, you have to remember your MySQL username and password.
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="username", password="password" ) print(mydb)
In this article, you have learned all about Python application with MySQL database.
If you want to use the database in your Python application, Then MySQL will be best because MySQL is the most popular database in the world.
If you like this article, please keep visiting for further Python MySQL operations.
Learn Python Programming