As we have created a database in our previous section, this section we will connect to that database using the python.
Code
import mysql.connector
cnx = mysql.connector.connect(user='root', password='Zoku&1236',
host='localhost',
database='mermaid')
print(cnx)
cnx.close()
Explanation
First we need to import MySql connector into our python script,
import mysql.connector
Next we need to create a reference variable to use methods and classes of mysql connector to connect our script to DB,
cnx = mysql.connector.connect(user='root', password='Zoku&1236',
host='localhost',
database='mermaid')
As the variable name suggest user refers to username and password to password for the user and localhost and name of database which you want connect to.
print(cnx)
In order to verify if you have established a connection, we will try to print the reference variable of connection's location address.
If we open a connection then it is also required to close then, we can use the close class.
cnx.close()