How to connect MySQL database using 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
The following example shows how to connect to the MySQL server:
To handle connection errors, use the try statement and catch all errors using the errors.Error exception:
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='username',
database='database_name')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
Another way is to pass the dictionary in the connect() function using ‘**’ operator