netx_iit

VNSGU-Practical-DHP-A-Oct-2024

Aug 24th, 2025 (edited)
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | Source Code | 0 0
  1. #Python Code for Medicine Table Operations
  2. import sqlite3
  3. import csv
  4.  
  5. # Connect / Create database
  6. conn = sqlite3.connect("medicine.db")
  7. cursor = conn.cursor()
  8.  
  9. # ------------------ A. Create Table & Insert Records ------------------
  10. cursor.execute("""
  11.    CREATE TABLE IF NOT EXISTS Medicine(
  12.        Med_Id INTEGER PRIMARY KEY,
  13.        Med_Name TEXT,
  14.        Qty INTEGER,
  15.        Rate REAL
  16.    )
  17. """)
  18.  
  19. # Insert at least 10 records
  20. medicines = [
  21.     (1, "Crocin", 10, 5.0),
  22.     (2, "Cough Syrup", 5, 50.0),
  23.     (3, "Coldact", 20, 2.5),
  24.     (4, "Calpol", 15, 3.0),
  25.     (5, "Cetrizine", 12, 1.5),
  26.     (6, "Paracetamol", 25, 2.0),
  27.     (7, "Disprin", 30, 1.0),
  28.     (8, "Cheston Cold", 8, 12.0),
  29.     (9, "Vitamin C", 18, 4.0),
  30.     (10, "Azithromycin", 10, 15.0)
  31. ]
  32.  
  33. cursor.executemany("INSERT OR IGNORE INTO Medicine VALUES (?, ?, ?, ?)", medicines)
  34. conn.commit()
  35. print("Inserted 10 records successfully.")
  36.  
  37. # ------------------ B. Add Column Total & Calculate ------------------
  38. try:
  39.     cursor.execute("ALTER TABLE Medicine ADD COLUMN Total REAL")
  40. except:
  41.     pass  # Ignore if column already exists
  42.  
  43. cursor.execute("UPDATE Medicine SET Total = Qty * Rate")
  44. conn.commit()
  45. print("Total column updated with Qty * Rate.")
  46.  
  47. # ------------------ C. Display Records with Name starting with 'C' ------------------
  48. print("\nMedicines starting with 'C':")
  49. cursor.execute("SELECT * FROM Medicine WHERE Med_Name LIKE 'C%'")
  50. rows = cursor.fetchall()
  51. for row in rows:
  52.     print(row)
  53.  
  54. # ------------------ D. Export Table Data to CSV ------------------
  55. cursor.execute("SELECT * FROM Medicine")
  56. all_data = cursor.fetchall()
  57.  
  58. with open("medicines.csv", "w", newline="") as f:
  59.     writer = csv.writer(f)
  60.     # Write header
  61.     writer.writerow([i[0] for i in cursor.description])
  62.     # Write data
  63.     writer.writerows(all_data)
  64.  
  65. print("\nData exported to medicines.csv successfully.")
  66.  
  67. # Close connection
  68. conn.close()
Tags: python sqlite
Advertisement
Add Comment
Please, Sign In to add comment