How to Connect Python with SQL Database?
In this article, we will learn how to connect SQL with Python using the MySQL Connector Python module. Below diagram illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data.

To create a connection between the MySQL database and Python the connect() method of mysql.connector module is used. We pass the database details like HostName, username and the password in the method call and then the method returns the connection object. Steps to Connect SQL with Python involve:
1. Install MySQL Database
Download and Install MySQL database in your system.
2. Open Command Prompt and Navigate to the location of PIP
After installing the MySQL database, open your Command prompt and run the commands given below to download and install "MySQL Connector". Here mysql.connector statement will help you to communicate with the MySQL database. Click here to see How to install PIP?
pip install mysql-connector-python

3. Test MySQL Connector
To check if the installation was successful or if you already installed "MySQL Connector" go to your IDE and run the given below code :
import mysql.connector
If the above code gets executed with no errors "MySQL Connector" is ready to be used.
4. Create Connection
Now to connect SQL with Python run the code given below in your IDE.
- mysql.connector allows Python programs to access MySQL databases.
- connect() method of the MySQL Connector class with the arguments will connect to MySQL and would return a MySQLConnection object if the connection is established successfully.
- host = "localhost": The
host
refers to the server where your MySQL database is hosted. In most cases for local development you can set it as"localhost"
. If the MySQL server is hosted on a different machine, you would replace"localhost"
with the appropriate IP address or hostname of that machine. - user = "yourusername": here "yourusername" should be the same username as you set during MySQL installation.
- password = "your_password": here "your_password" should be the same password as you set during MySQL installation.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "your_password"
)
print(mydb)
Output:
Now that we know how to connect SQL database with python we can use it to create databases and tables, store data and manipulate them all directly through python. We can create many projects using this way.