Python MySQL Database Connection
In this article, I will demonstrate how to perform MySQL database connectivity in Python using simple 5 steps.
Note: We are using MySQL Connector Python to connect MySQL.
Arguments required to connect MySQL from Python
You need to know the following detail of the MySQL server to perform the connection from Python.
Username:
UserName is the username that you use to work with MySQL Server. The default username for the MySQL database is a root
Password:
Password is given by the user at the time of installing the MySQL database. If you are using root then you won’t need the password.
Host Name:
Host Name is the server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost, or it’s IP, i.e. 127.0.0.0
Database Name:
Database name to which you want to connect. Here we are using Database named ‘Electronics‘ because we have already created this for our example.
Note: We are using the MySQL Connector Python module to communicate with MySQL Server.
Steps to connect MySQL database in Python using MySQL Connector Python
1. Install MySQL Connector Python using pip.
2. Use the mysql.connector.connect() method of MySQL Connector Python with required parameters to connect MySQL.
3. Use the connection object returned by a connect() method to create a cursor object to perform Database Operations.
4. The cursor.execute() to execute SQL queries from Python.
5. Close the Cursor object using a cursor.close() and MySQL database connection using connection.close() after your work completes.
6. Catch Exception if any that may occur during this process.
Python Example to connect MySQL Database
To connect the MySQL database, you must know the database name you want to connect. Run below query on MySQL console if you have not created any database in MySQL. Otherwise, you can skip the below query.
Create Database in MySQL