BestCloudHostingASP.NET | 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()
It is also possible to create connection objects using the connection.MySQLConnection() class:
from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
cnx.close()
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 exist")
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()
Using the Connector/Python C Extension
As of Connector/Python 2.1.1, the use_pure
connection argument determines whether to connect using a pure Python interface to MySQL, or a C Extension that uses the MySQL C client library (. The default is True
(use the pure Python implementation). Setting use_pure
to False
causes the connection to use the C Extension if your Connector/Python installation includes it. The following examples are similar to others shown previously but with the includion of use_pure=False
.
Connect by naming arguments in the connect()
call:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees',
use_pure=False)
cnx.close()
Connect using an argument dictionary:
import mysql.connector
config = {
'user': 'scott',
'password': 'tiger',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
'use_pure': False,
}
cnx = mysql.connector.connect(**config)
cnx.close()
It is also possible to use the C Extension directly, by importing the _mysql_connector
module rather than the mysql.connector
module