☞ A database connection object controls the connection to the database.
☞ Connection object represents a unique session with a database connected form within a program.
☞ To establish a connection, we need to perform following steps :
Step 1 : Import mysql.connector module and open a connection
Step 2 : Check the connection using connecton_id attribute or is_connected() function
☞ Example 1 :
import mysql.connector as m
mydb = m.connect(host='localhost', user='root', password='123')
print(mydb.connection_id) #connection_id is for checking purpose only
☞ Output :
15 #15 is your connection id for current session
☞ Example 2 :
import mysql.connector as m
mydb = m.connect(host='localhost', user='root', password='123')
if mydb.is_connected(): #is_connected() is for checking purpose only
print(“Connection established successfully”)
else:
print(“Connection not established”)
☞ Output :
☞ To install the mysql.connector module, you need to run the following command on the command prompt(cmd).