How to Connect MySQL Database with Python

In this Python MySQL tutorial we want to learn How to Connect MySQL Database with Python, so Python is powerful programming language and it has different libraries for working with MySQL database, in this article we want to talk about MySQL Connector.

 

 

First of all we need to install MySQL Connector for Python and you can use pip for that.

 

 

 

After that we have installed the required library, and we need to import our modules.

 

 

Now we can establish a connection to the MySQL database. for this we need to provide the necessary information, such as host name, port number, database name, username and password.

 

 

 

Run the code and this will be the result

How to Connect MySQL Database with Python
How to Connect MySQL Database with Python

 

 

 

Now that we have successfully connected to MySQL database, we can perform different operations on it. for example we can create a new table, insert data into an existing table or retrieve data from the database.

 

 

In here I am retrieving data from books table.

In the above code, first of all we have created a cursor object using connection.cursor() method. after that we execute a SQL query to retrieve all the rows from the books table using cursor.execute() method. and lastly we fetch all the rows using cursor.fetchall() method and loop through them to print each row.

 

 

 

This will be the result

MySQL and Python
MySQL and Python

 

 

 

This is the complete example code that connects to MySQL database, creates a table, inserts some data and retrieves it:

 

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×