Advertisement
GamerBhai02

APP Exp 7

Apr 17th, 2025
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | Source Code | 0 0
  1. import sqlite3
  2.  
  3. def connect_db():
  4.     db = sqlite3.connect("demodb.db")
  5.     print("Database connected")
  6.     return db
  7.  
  8. def create_table(db):
  9.     cursor = db.cursor()
  10.     cursor.execute("create table if not exists users(id integer primary key,name text,age integer)")
  11.     print("Table created")
  12.     db.commit()
  13.  
  14. def insert_data(db,id,name,age):
  15.     cursor = db.cursor()
  16.     cursor.execute("insert into users(id,name,age) values(?,?,?)",(id,name,age))
  17.     print("\nData inserted into table")
  18.     db.commit()
  19.  
  20. def fetch_data(db):
  21.     cursor = db.cursor()
  22.     cursor.execute("select * from users")
  23.     rows = cursor.fetchall()
  24.     print("Fetching...")
  25.     for i in rows:
  26.         print(i)
  27.     db.commit()
  28.  
  29. def update_data(db,id,age):
  30.     cursor = db.cursor()
  31.     cursor.execute("update users set age=? where id=?",(age,id))
  32.     print("\nTable updated")
  33.     db.commit()
  34.  
  35. def delete_data(db,id):
  36.     cursor = db.cursor()
  37.     cursor.execute("delete from users where id=?",(id,))
  38.     print("\nData deleted")
  39.     db.commit()
  40.  
  41. if __name__=="__main__":
  42.     db = connect_db()
  43.     create_table(db)
  44.     insert_data(db,1,"Talha",19)
  45.     insert_data(db,2,"Oubed",16)
  46.     fetch_data(db)
  47.     update_data(db,2,17)
  48.     fetch_data(db)
  49.     delete_data(db,2)
  50.     fetch_data(db)
  51.     db.close()
  52.     print("Database disconnected")
Tags: exp7
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement