How to Insert Data in Database Table Using Python Database Connection

Python course with 57 real-time projects - Learn Python

Program 1

import MySQLdb
from MySQLdb import *
try:
    #Connection
    con=MySQLdb.Connect(host="localhost",user="root",password="root",database="dataflair")
    print("Connection Success")
    #User Input
    empid=int(input("Enter Employee ID:"))
    empname=input("Enter Employee Name:")
    empdept=input("Enter Employee Department:")
    empsal = int(input("Enter Employee Salary:"))

    #Query Execution

    sql="insert into employee values('%d','%s','%s','%d')"
    value=(empid,empname,empdept,empsal)
    cur=con.cursor()
    cur.execute(sql % value)

    con.commit()
    print("recrod inserted",cur.rowcount)
except Exception as obj:
    print(obj)
finally:
    con.close()
    print("Connection closed")

 

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *