In the last article, we have learned about how to connect python with MySQL database.In this article, we are going to learn how to Insert data into MYSQL database using python.
Insert Data Into MYSQL Database Using Python
Before reading this article please install MySQL on your local machine.After installing it, make sure it is running on your system.Now create a database and a table having two rows using PHPMyAdmin or shell.
If you don’t know how to do it, Don’t worry.I have made a simple tutorial on how to insert delete and update data using both PHPMyAdmin and shell.
As you can see, I am in the python database and created a table called pytable with the following structure.This table has two fields such as name and charecter(*oops spelling mistake 😛 ).Now I want to insert some names with their corresponding characters into this table using python programming.
Simple Python Script To Insert Data Into MYSQL Database
Firstly I would like to present my python script to insert data into the database using python.
con = mysql.connector.connect(user='root',password='',host='localhost',database='python')
cur = con.cursor()
cur.execute("""INSERT INTO pytable VALUES (%s,%s)""",("prathap","great"))
As we discussed in the previous article, the first two lines are just to import modules and connecting to the MySQL database with your DB details.Then you need to create cursor object that assigns to cur variable which helps you to execute all your further queries.
cur.execute() enables us to execute any MYSQL query.In our case, we are going to execute the insert query.
Basically, In MYSQL, Inserting and Retrieving queries are so different.One should be aware of that certain table fields to insert the data.Our table has only two fields (“name” and “charecter”).So we can’t give 3 values to this query.So that we can take this as an advantage in classes and methods made inserting easy. I will write that article soon 🙂
So the above query is inserting “prathap” and “good” into pytable using string formatting method. Now open your PHPMyAdmin and navigate to that certain table to check whether the data is inserted or not.
Please, Like Our Facebook Page For More Updates and Comment Here.