Today, We will learn on how to connect Python with Mysql. This tutorial will let you know how python can be used with database applications. Before starting with our tutorial, we need to have MySQL installed in your System.
You can download the MySQL database form https://www.mysql.com/downloads/
In order to connect with MySQL, Python requires Mysql Driver. So, as the next step towards database connectivity we can now install MySQL Driver. Open Command Prompt or terminal and type the following commands. We will be using PIP for faster and safer installation of the packages.
Command to Install MySQL Connector
python -m pip install mysql-connector
Now, we have done installing Mysql Connector. Our next process is to test the installation. Let's do that by simply importing the mysql connector package.
If the above import statement did not produce any errors or warnings, then hurrah! we've successfully installed MySQL Connector.
Our Next Step is to, Create a Connection to MySQL Database:
Remember the username and password you have provided during MySQL Installation? Default username is root and Password must be left blank.
import mysql.connector new_database = mysql.connector.connect( host="localhost", user="root", passwd="" )
In the above code block, we have used host, user and passwd. We need to use another parameter port. This parameter is used because on some systems the default port number used by mysql database will be different. The default port used by MySQL Database is 3306. That's why we have not used the port parameter. So, if the database is on different port we need to just add the port prameter to the connector function.
import mysql.connector new_database = mysql.connector.connect( host="localhost", port="3308", user="root", passwd="" )
Now, we have successfully connected to the database.
We'll be going through how to create a database in our next article.