Connect to MySQL using PyMySQL in Python
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database.
What is PyMySQL?
This package contains a pure-Python MySQL client library, based on PEP 249.
MySQL Server – one of the following :
- MySQL >= 5.5
- MariaDB >= 5.5
This module does not come built-in with Python. You have to install it externally. To install this type the below command in the terminal.
pip install PyMySQL
Connecting to MySQL
The proper way to get an instance of this class is to call connect() method. This method establishes a connection to the MySQL database and accepts several arguments:
- host – Host where the database server is located
- user – Username to log in as
- password – Password to use.
- database – Database to use, None to not use a particular one.
- port – MySQL port to use, default is usually OK. (default: 3306)
Example 1: Let’s connect to the MySQL server.
Example 2: Let’s try to access a table from the database
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course