Q:

Insertion of Records to Database in Python

belongs to collection: Python Database (SQL/MySQL) Programs

0

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.

Problem Description: 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.

Algorithm:

  • Step 1: Create a connection using connect method.
  • Step 2: Take input from the user.
  • Step 3: Create a Query, using the inserted information.
  • Step 4: Execute the query which will enter the information to the table.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to illustrate Insertion of records to database in Python

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Fetch employee details from the database whose sal... >>
<< Python program to display SQL table content...