ADVERTISEMENT
ADVERTISEMENT

Insertion of Records to Database in Python

Here, we will see a program to illustrate the insertion of records to a database in Python.
Submitted by Shivang Yadav, on February 16, 2021

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

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

Python database (SQL/MySQL) programs »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.