Hi! Could we please enable some services and cookies to improve your experience and our website?

SQLize Online / PHPize Online  /  SQLtest Online

A A A
Share code      Blog   Popular   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear
import sqlite3 # Create database connection and table def setup_database(): conn = sqlite3.connect('Hospital.db') cursor = conn.cursor() # Create Patient table cursor.execute(''' CREATE TABLE IF NOT EXISTS Patient ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, issue TEXT NOT NULL, age INTEGER NOT NULL ) ''') conn.commit() return conn, cursor # Insert new patient def insert_patient(cursor, conn, id, name, issue, age): cursor.execute(''' INSERT INTO Patient (id, name, issue, age) VALUES (?, ?, ?, ?) ''', (id, name, issue, age)) conn.commit() # Delete patient by ID def delete_patient(cursor, conn, id): cursor.execute('DELETE FROM Patient WHERE id = ?', (id,)) conn.commit() # Update patient information def update_patient(cursor, conn, id, name=None, issue=None, age=None): updates = [] params = [] if name: updates.append("name = ?") params.append(name) if issue: updates.append("issue = ?") params.append(issue) if age: updates.append("age = ?") params.append(age) if not updates: return # No updates params.append(id) update_query = "UPDATE Patient SET " + ", ".join(updates) + " WHERE id = ?" cursor.execute(update_query, params) conn.commit() # Display all patients def display_patients(cursor): cursor.execute("SELECT * FROM Patient") patients = cursor.fetchall() if not patients: print("No patients found") return print("\nID\tName\tAge\tIssue") print("-" * 30) for patient in patients: print(f"{patient[0]}\t{patient[1]}\t{patient[3]}\t{patient[2]}") # Main execution def main(): conn, cursor = setup_database() # Insert initial patients patients_data = [ (133, 'Malak', 'pressure', 25), (566, 'Ahmed', 'sugar', 26), (4455, 'Mina', 'sugar', 28) ] for data in patients_data: insert_patient(cursor, conn, *data) print("Initial patients:") display_patients(cursor) # Add Mona insert_patient(cursor, conn, 34566, 'Mona', 'sugar', 30) print("\nAfter adding Mona:") display_patients(cursor) # Update Ahmed's issue update_patient(cursor, conn, 566, issue='diabetes') print("\nAfter updating Ahmed's issue:") display_patients(cursor) # Delete Malak delete_patient(cursor, conn, 133) print("\nAfter deleting Malak:") display_patients(cursor) conn.close() if __name__ == "__main__": main()

Stuck with a problem? Got Error? Ask ChatGPT!