How To Connect MySQL Database From Python Application and Execute Sql Query with Examples


MySQL is very popular and open source database server. Python is old but lately discovered language. In this tutorial we will look how to use this popular techs in our applications in order to run sql queries.

Install Python MySQL Connector

In order to connect MySQL database from Python application we need some libraries. There are different libraries those supports running sql queries on MySQL but we will stick with mysql-connector-python3 .

Fedora, CentOS, RHEL

We can install mysql-connector-python3 library with the following command. This requires root privileges.

Debian, Ubuntu,Mint

We can install mysql-connector-python3 library with the following command. This requires root privileges.


Pip can be used to install mysql connector library.

Load MySQL Library

In order to use MySQL library we need to import it into our application. We will use import statement to import library which is named mysql.connector .

Connect MySQL Database with Username and Password

Now we can connect to the database. While connecting MySQL database we to provide following parameters to the mysql.connector.connect function

  • user is the username to authenticate
  • password is the password of the user
  • host the database server hostname or IP address
  • database is optional which provides the database name

Run and Execute SQL Query

In order to run SQL query we need to create a cursor which is like a SQL query window in GUI SQL tools. We will use dbcon.cursor() and then use created cursor objects execute function by providing the SQL.

LEARN MORE  Linux Bash Alias and Shortcuts

Print and List Returned Data

After executing the query the results will be saved to the cursor object named cur . We can get and list returned information from cur object. Provided data is stored in a list format. So we can use loops to iterate and print.

Close MySQL Connection

One of the most important part of database programming is using sources very strictly. In order to prevent performance problems we need to close the connection to the MySQL database after finishing job. We will use close() function of connection object.

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)