Hello Python Lovers, I am here with a new and detailed tutorial on how to connect python to MySQL database. In the end of the article, you will have some idea on how to access databases using python and can manipulate your data.
Basically, When we are working with files on python,PHP or any other scripting language.We need to store the data that can be retrieved.Data can be anything like books data,Usernames, Passwords etc.Even you can write that data to a text file, It is not recommended because sometimes you need to save the larger data.So Database is introduced to do those things.
A Database is an application that collects the different kinds of Information and stores in its tables and columns.So one can easily store, retrieve, update and manipulate the data with database software.
Most of the earlier database software are just used to do basic operations like updating and retrieving.But those don’t support for advanced projects like E-commerce websites etc.Because, In those projects, the data of one table must be connected with the data of another table.Hence RDBMS (
Hence RDBMS (Relational Database Management System) is introduced.It will have various keys to connect with the other tables in that database. the best RDBMS which is widely using for various web applications is the MYSQL.
How To Connect Python To Mysql Database
Firstly, We need to Download the MYSQL-CONNECT module to connect to the database from python.
If you open the above link, you will likely have many options and should download the suitable version for your windows.Now install it and it will extract all the module files to your python.
Now check Whether it is installed properly or not.Open your python . write this below command and press Enter.If you have got nothing congrats you installed it Successfully.
Before using the database and storing values inside it.First, you need to install MYSQL on your local windows machine.
I wrote some simple code to connect to the database using python exceptional handling.
In the first line, we just imported mysql.connector module to access its methods for further use.
We are trying to connect to the database in the try: and If it doesn’t connect then it will go to except: part.
In the try: we created a con variable using mysql.connector.connect method which typically has four parameters user,password,host,database.I have assigned my database details.
So If the database is not connected successfully.You will get something like as above ( Please Check Your DB Details ).In later articles, you will learn how to insert data into database using python
How This Works For You.
Please, Like Our Facebook Page For More Updates and Comment Here.