Example 1
1 2 3 4 5 6 |
import mysql.connector cnx = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='mydb') cnx.close() |
Example 2
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='root', database='mydb') 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() |
Example 3
If you have lots of connection arguments, it’s best to keep them in a dictionary and use the ** operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import mysql.connector config = { 'user': 'root', 'password': '', 'host': '127.0.0.1', 'database': 'mydb', 'raise_on_warnings': True, } cnx = mysql.connector.connect(**config) cnx.close() |