Open Menu dzosoft
Close Menu dzosoft
All About Computer Science and Technology

                twitter instagram facebook pinterest
search on the site
 
 
 

How to connect MySQL database using Connector/Python

 
 
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:
import mysql.connector

cnx = mysql.connector.connect(user='username', password='password',
                              host='localhost',
                              database='database_name')
cnx.close()

Also for the same, we can use connection.MySQLConnection() class instead of connect():
 

Example

from mysql.connector import (connection)

cnx = connection.MySQLConnection(user='username', password='password',
                                 host='localhost',
                                 database='database_name')
cnx.close()

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
 

Example

import mysql.connector

config = {
  'user': 'username',
  'password': 'password',
  'host': 'localhost',
  'database': 'database_name',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

cnx.close()

Leave comment
          

Save nickname and email in this browser for the next time.



All about computer science and technology