Python MySQL Database Connection

In this Python MySQL tutorial we want to learn about Python MySQL Database Connection, 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

Python MySQL Database Connection
Python MySQL Database Connection

 

 

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 book 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 book 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

Python MySQL Database Connection
Python MySQL Database Connection

 

 

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

 

 

 

Learn More

Leave a Comment