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.connector
cnx = mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
Section 6.7.1, “Connector/Python Connection Arguments” describes the permitted connection arguments.
It is also possible to create connection objects using the connection.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 the connect()
constructor or the class directly) are valid and functionally
equal, but using connect()
is preferred and
used by most examples in this manual.
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='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()
Defining Logger options, a reconnection routine, and defined as a connection method named connect_to_mysql:
import logging
import time
import mysql.connector
# Set up logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# Log to console
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
# Also log to a file
file_handler = logging.FileHandler("cpy-errors.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
def connect_to_mysql(config, attempts=3, delay=2):
attempt = 1
# Implement a reconnection routine
while attempt < attempts + 1:
try:
return mysql.connector.connect(**config)
except (mysql.connector.Error, IOError) as err:
if (attempts is attempt):
# Attempts to reconnect failed; returning None
logger.info("Failed to connect, exiting without a connection: %s", err)
return None
logger.info(
"Connection failed: %s. Retrying (%d/%d)...",
err,
attempt,
attempts-1,
)
# progressive reconnect delay
time.sleep(delay ** attempt)
attempt += 1
return None
Connecting and using the Sakila database using the above routine,
assuming it's defined in a file named
myconnection.py
:
from myconnection import connect_to_mysql
config = {
"host": "127.0.0.1",
"user": "user",
"password": "pass",
"database": "sakila",
}
cnx = connect_to_mysql(config, attempts=3)
if cnx and cnx.is_connected():
with cnx.cursor() as cursor:
result = cursor.execute("SELECT * FROM actor LIMIT 5")
rows = cursor.fetchall()
for rows in rows:
print(rows)
cnx.close()
else:
print("Could not connect")
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 the use_pure
connection
argument. It defaults to False
as of MySQL 8,
meaning the C extension is used. If the C extension is not
available on the system then use_pure
defaults
to True
. Setting
use_pure=False
causes the connection to use the
C Extension if your Connector/Python installation includes it, while
use_pure=True
to False
means
the Python implementation is used if available.
The use_pure
option and C extension were
added in Connector/Python 2.1.1.
The following example shows how to set use_pure
to 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_connector
module rather than the
mysql.connector
module. For more information,
see The _mysql_connector C Extension Module.