Open Menu dzosoft
Close Menu dzosoft

   TOUT SUR L'INFORMATIQUE ET LA TECHNOLOGIE


                             




Dazzle with your smile!

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


También te puede interesar


Comment installer Python sur Windows

Comment écrire votre premier programme Python

Comment verrouiller un PC avec une commande vocale à l'aide de Python

Comment dessiner des formes avec Python

Comment créer des lectures et des écritures dans un fichier en python

Comment créer votre propre assistant personnel à l'aide de ChatGPT et Python

Comment créer et initialiser un dictionnaire Python


Leave comment
          

Enregistrez le pseudo et l'e-mail dans ce navigateur pour la prochaine fois.



Cargando...     

Nord VPN