Connect MySQL database using MySQL-Connector Python
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.
MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies.
Connecting to the Database
In the following example we will be connecting to MySQL database using connect()
Example:
Python3
# Python program to connect# to mysql databaseimport mysql.connector# Connecting from the serverconn = mysql.connector.connect(user = 'username', host = 'localhost', database = 'database_name')print(conn)# Disconnecting from the serverconn.close() |
Output:

Also for the same, we can use connection.MySQLConnection() class instead of connect():
Example:
Python3
# Python program to connect# to mysql databasefrom mysql.connector import connection# Connecting to the serverconn = connection.MySQLConnection(user = 'username', host = 'localhost', database = 'database_name')print(conn)# Disconnecting from the serverconn.close() |
Output:

Another way is to pass the dictionary in the connect() function using ‘**’ operator:
Example:
Python3
# Python program to connect# to mysql databasefrom mysql.connector import connectiondict = { 'user': 'root', 'host': 'localhost', 'database': 'College'}# Connecting to the serverconn = connection.MySQLConnection(**dict)print(conn)# Disconnecting from the serverconn.close() |
Output:





.png)