Menu Close

Connect Python To MySQL Database

How to Connect Python To MySQL Database

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 applications with MySQL databases.

MySQL Database

MySQL is one of the most popular open-source relational database management systems written in C and C++ programming languages. MySQL database server is a fast, reliable, and easy-to-use database management system. You can use the MySQL database management system for your python applications with few configurations.

To connect Python application to MySQL database, You should have MySQL installed in your machine or computer system.

You can download MySQL to 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.

connect_mysql.py

import mysql.connector
print('successful')

If you get ‘successful‘ message after executing above python file, then MySQL driver successfully installed in your machine.

Create connection

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.

connect_mysql.py

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="username",
	password="password"
	
)

print(mydb)

Conclusion

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


Previous Article
Next Article

Related Posts

Leave a Reply