5.1 Connecting to MySQL Using Connector/Python

Theconnect()constructor creates a connection to the MySQL server and returns aMySQLConnectionobject.

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

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

Section 7.1, “Connector/Python Connection Arguments”describes the permitted connection arguments.

It is also possible to create connection objects using theconnection.MySQLConnection()class:

from mysql.connector import (connection) cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()

Both forms (either using theconnect()constructor or the class directly) are valid and functionally equal, but usingconnect()is preferred and used by most examples in this manual.

To handle connection errors, use thetrystatement and catch all errors using theerrors.Errorexception:

import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott', database='employ') 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()

Defining connection arguments in a dictionary and using the**operator is another option:

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

Using the Connector/Python Python or C Extension

Connector/Python offers two implementations: a pure Python interface and a C extension that uses the MySQL C client library (see第八章,The Connector/Python C Extension). This can be configured at runtime using theuse_pureconnection argument. It defaults toFalseas of MySQL 8, meaning the C extension is used. If the C extension is not available on the system thenuse_puredefaults toTrue. Settinguse_pure=Falsecauses the connection to use the C Extension if your Connector/Python installation includes it, whileuse_pure=TruetoFalsemeans the Python implementation is used if available.

Note

Theuse_pureoption and C extension were added in Connector/Python 2.1.1.

The following example shows how to setuse_pureto False.

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

It is also possible to use the C Extension directly by importing the_mysql_connectormodule rather than themysql.connectormodule. For more information, seeSection 8.2, “The _mysql_connector C Extension Module”.