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='tiger',
host='127.0.0.1',
database='employees')
cnx.close()See Section 21.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.connector
from mysql.connector import errorcode
try:
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.connector
config = {
'user': 'scott',
'password': 'tiger',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
}
cnx = mysql.connector.connect(**config)
cnx.close()

User Comments
Add your own comment.