Python Database – MySQL Connector in Python

In this Python Python Database tutorial we want to learn about MySQL Connector in Python, so as you know that 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.

 

 

 

Connecting 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, in here my database name is codeloop.

 

 

 

Now we have our database, make sure that you already have created your database, in our case our database name is codeloop, now it is time to create a table and we want to create books table in our MySQL database.

 

 

 

Now if you see we have this table, but we don’t have any data.

Python Database - MySQL Connector in Python
Python Database – MySQL Connector in Python

 

 

 

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, now we want to add some data to our Python MySQL database table.

 

 

 

Now if you check your MySQL Database, we have some data.

MySQL Connector in Python
MySQL Connector in Python

 

 

 

 

Now let’s select all data from our database. this code selects all records from books 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 Select All Data
Python MySQL Connector Select All Data

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×