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:

  1. Inmport the MySQL connect using import statement.
    import  pymysql as ps
  2. Connect to database using connect() method.
    cn=ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
  3. Input the records from the user that you want to insert.
  4. Create a Query with the input records.
     query="insert into products values('{}','{}',{},'{}')".format(pid,pn,pr,md)
  5. 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 »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.