Open Menu dzosoft
Close Menu dzosoft

   ALL ABOUT COMPUTER SCIENCE AND TECHNOLOGY


                             




A MALE SOLUTION TO PROSTATE PROBLEMS!

Publish perfectly-optimized content in 1-click









 
 
 

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()


It might also interest you


How to install Python on Windows

How to write your first Python program

How to lock PC with voice command using Python

How to draw shapes with python

How to create read and write to a file in python

How to create your own personal assistant using ChatGPT and Python

How to create and initialize a Python dictionary


Leave comment
          

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



Loading...     
close publicity
Japanese ritual of tranquility and... slim figure!