Home »
Python »
Python Programs
Insert Records to MySQL Table in Python
Python MySQL | Insert Records: In this tutorial, we will learn how to insert records to MySQL table with the help of Python program?
By Shivang Yadav Last updated : April 21, 2023
We need to take input from users about all information to be fed in the tables and then insert it into the database using Python.
We will take input from the user for all table columns and then create a query to insert the information into the database using Python.
How to Insert Records to MySQL Table in Python?
The following steps are used to insert records to MySQL table:
- Inmport the MySQL connect using import statement.
import pymysql as ps
- Connect to database using connect() method.
cn=ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
- Input the records from the user that you want to insert.
- Create a Query with the input records.
query="insert into products values('{}','{}',{},'{}')".format(pid,pn,pr,md)
- Execute the query which will insert the data to the MySQL table.
cmd.execute(query)
Python Program to Insert Records to MySQL Table
import pymysql as ps
try:
cn=ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
cmd=cn.cursor()
pid=input("Enter Product Id:")
pn=input("Enter Product Name:")
pr = input("Enter Product Rate:")
md = input("Enter Mf. Date:")
query="insert into products values('{}','{}',{},'{}')".format(pid,pn,pr,md)
cmd.execute(query)
cn.commit()
cn.close()
print("Record Submitted")
except Exception as e:
print(e)
Output
Enter Product Id: 001
Enter Product Name: Sensor 421
Enter Product Rate: 250
Enter Mf. Date: 3.2.2020
Record Submitted
Python MySQL Programs »