Python MySQL Connector

In this Python MySQL tutorial we want to learn about Python MySQL Connector, so Python is popular language, and you can use Python in different fields like Web Development, GUI Development and scientific computing. some times when you are doing data analysis in Python, than you will need a database like MySQL database, in this article we want to talk about Python MySQL Connector, it is a library that provides an easy and efficient way to connect  and interact with MySQL databases using Python.

 

 

What is MySQL Connector ?

MySQL Connector is a library that allows Python developers to connect and communicate with MySQL databases. this library is written in pure Python and is compatible with both Python 2 and Python 3.

 

 

How to Install MySQL Connector ?

Now let’s learn that how we can install MySQL Connector, you can use pip for the installation like this.

 

 

How to Connect Python with MySQL Database ?

Before we interact with MySQL database, we need to establish a connection to it. for this we need to provide the necessary credentials such as host name, username, password and database name. this is an example of how to connect to a MySQL database:

 

 

If there is a connection, you will see this result

Python MySQL Connector
Python MySQL Connector

 

 

After that we have a connection to MySQL database, and we can execute SQL queries to read or modify data. the simplest way to execute a query is to create a cursor object from the connection and call execute() method like this.

This code selects all records from book table and prints them to the console. fetchall() method retrieves all the rows returned by the query and returns them as a list of tuples. we use for loop to iterate over the list and print each tuple.

 

 

This will be the result

Python MySQL Connector
Python MySQL Connector

 

 

For inserting data into MySQL database, we need to create an INSERT query and execute it using a cursor object. this is an example:

 

 

And if you see your WAMP Server, a new record is added at the end.

Python MySQL Connector
Python MySQL Connector

 

 

Learn More

Leave a Comment