Spec-Zone .ru
спецификации, руководства, описания, API

22.6.4.1. Connecting to MySQL Using Connector/Python

The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object.

The following example shows how to connect to the MySQL server:

import mysql.connectorcnx = mysql.connector.connect(user='scott', password='tiger',                              host='127.0.0.1',                              database='employees')cnx.close()

See Section 22.6.6, "Connector/Python Connection Arguments" for all possible connection arguments.

It is also possible to create connection objects using the connection.MySQLConnection() class. Both methods, using the connect() constructor, or the class directly, are valid and functionally equal, but using connector() is preferred and is used in most examples in this manual.

To handle connection errors, use the try statement and catch all errors using the errors.Error exception:

import mysql.connectorfrom mysql.connector import errorcodetry:  cnx = mysql.connector.connect(user='scott',                                database='testt')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 exists")  else:    print(err)else:  cnx.close()

If you have lots of connection arguments, it's best to keep them in a dictionary and use the ** operator:

import mysql.connectorconfig = {  'user': 'scott',  'password': 'tiger',  'host': '127.0.0.1',  'database': 'employees',  'raise_on_warnings': True,}cnx = mysql.connector.connect(**config)cnx.close()