0
Copy the following code and save it as pythondb.py

import MySQLdb
db=MySQLdb.connect("localhost","root","password","dbname")
cursor=db.cursor()

print "1.Insert values in table \n 2.Update values in Table \n 3.Show All \n 4.Delete By Roll.No"

def inserts():
  i1=input("Enter rno -")
  i2=raw_input("Enter Name -")
  sql="insert into stud values( '" +str(i1)+ "','"+str(i2)+"')"
  cursor.execute(sql)
  db.commit()
  print "-- Values inserted sucessfully --"

def update():
  i1=input("Rno to update -")
  i2=raw_input("Enter New Name -")
  sql="update stud set name ='"+str(i2)+"' where rno= '" +str(i1)+ "'"
  cursor.execute(sql)
  db.commit()
  print "-- Updated sucessfully --"

def show():
  print "Rno  Name "
  sql="select * from stud"
  cursor.execute(sql)
  result=cursor.fetchall()
  for row in result:
    rno=row[0]
    name=row[1]
    print "%d | %s "%(rno,name)

def delete():
  i1=input("Enter rno to Delete -")
  sql="delete from stud where rno='" +str(i1)+ "' "
  cursor.execute(sql)
  print "-- Deleted  sucessfully --" 

while 1:
 op=input("Enter your opton:-")

 if(op==1):
  inserts()
 elif(op==2):
  update()
 elif(op==3):
  show()
 elif(op==4):
  delete()
 elif(op==0):
  break

db.close()


Run it as,

python filename.py

e.g python pythondb.py


Post a Comment

 
Top