Most of the time the data gathered from various sources is initially stored inside a database as its volume (size) will be huge, and handling such a huge amount of data directly inside python becomes difficult due to memory constraint. So that is why initially the data is kept inside the databases, and fetched by connecting to the database with a particular programming language in our case it is python.
Start by Installing the MySQL connector/driver.
A database driver/connector is a small software that enables a programming language to connect to and interact with a database system. Before Python can communicate with a database from a specific vendor, it requires a custom driver.
So different databases require a different driver/connector to connect with the database.
So in python you need to install a python MySQL connector to interact with a MySQL database.
In the next step, you simply need to import the MySQL connector as it contains important modules like the connect() method for connecting python to the database.
Next, to communicate with a MySQL server, you must first establish a connection with the Connect() method from the MySQL.connector module.
This function accepts host, user, and password inputs and returns a MySQLConnection object.
These credentials can be received as input from the user and password to connect to the database.
You also need to utilize a cursor() method to run a SQL query, which abstracts away the access to database records.
The MySQLCursor class in MySQL Connector/Python creates objects that can be used to execute MySQL queries in python. A cursor is a representation of the MySQLCursor class.
When establishing a connection to the MySQL server, it’s always a good practice to handle the errors that may arise during establishing a connection using the exception handling concept.
This is why you should use the “try” block for establishing the connection and use the “except” block to handle and print any exceptions you might come across.
And now successfully established the connection with the MySQL server.
To conclude, the MySQL connector provides a straightforward way to connect to python and execute queries through it. Due to which it becomes a lot easier to handle, manipulate and import the data inside python.
To learn more about this and how to implement end to end data science project from scratch, go to our website and enroll in our guided data science project program.