fork download
  1. import sqlite3
  2.  
  3. # Database connection
  4. conn = sqlite3.connect('railway_management.db')
  5. cursor = conn.cursor()
  6.  
  7. # Create tables for train and reservation data
  8. cursor.execute("""
  9. CREATE TABLE IF NOT EXISTS trains (
  10. train_id INTEGER PRIMARY KEY AUTOINCREMENT,
  11. train_name TEXT,
  12. source TEXT,
  13. destination TEXT,
  14. departure_time TEXT,
  15. available_seats INTEGER
  16. )
  17. """)
  18.  
  19. cursor.execute("""
  20. CREATE TABLE IF NOT EXISTS reservations (
  21. reservation_id INTEGER PRIMARY KEY AUTOINCREMENT,
  22. user_name TEXT,
  23. train_id INTEGER,
  24. seat_count INTEGER,
  25. status TEXT,
  26. FOREIGN KEY (train_id) REFERENCES trains (train_id)
  27. )
  28. """)
  29. conn.commit()
  30.  
  31. # Class representing a train
  32. class Train:
  33. def __init__(self, train_name, source, destination, departure_time, available_seats):
  34. self.train_name = train_name
  35. self.source = source
  36. self.destination = destination
  37. self.departure_time = departure_time
  38. self.available_seats = available_seats
  39.  
  40. def add_train(self):
  41. cursor.execute("""
  42. INSERT INTO trains (train_name, source, destination, departure_time, available_seats)
  43. VALUES (?, ?, ?, ?, ?)
  44. """, (self.train_name, self.source, self.destination, self.departure_time, self.available_seats))
  45. conn.commit()
  46.  
  47. def show_trains(self):
  48. cursor.execute("SELECT * FROM trains")
  49. for row in cursor.fetchall():
  50. print(f"Train ID: {row[0]}, Name: {row[1]}, Source: {row[2]}, Destination: {row[3]}, Departure: {row[4]}, Available Seats: {row[5]}")
  51.  
  52. # Class to manage reservations
  53. class Reservation:
  54. def __init__(self, user_name, train_id, seat_count):
  55. self.user_name = user_name
  56. self.train_id = train_id
  57. self.seat_count = seat_count
  58.  
  59. def book_ticket(self):
  60. cursor.execute("SELECT available_seats FROM trains WHERE train_id = ?", (self.train_id,))
  61. available_seats = cursor.fetchone()[0]
  62.  
  63. if available_seats >= self.seat_count:
  64. cursor.execute("INSERT INTO reservations (user_name, train_id, seat_count, status) VALUES (?, ?, ?, ?)",
  65. (self.user_name, self.train_id, self.seat_count, 'Booked'))
  66. cursor.execute("UPDATE trains SET available_seats = available_seats - ? WHERE train_id = ?",
  67. (self.seat_count, self.train_id))
  68. conn.commit()
  69. print("Ticket booked successfully!")
  70. else:
  71. print("Not enough available seats.")
  72.  
  73. def cancel_ticket(self, reservation_id):
  74. cursor.execute("SELECT seat_count, train_id FROM reservations WHERE reservation_id = ?", (reservation_id,))
  75. reservation = cursor.fetchone()
  76.  
  77. if reservation:
  78. seat_count, train_id = reservation
  79. cursor.execute("UPDATE trains SET available_seats = available_seats + ? WHERE train_id = ?",
  80. (seat_count, train_id))
  81. cursor.execute("DELETE FROM reservations WHERE reservation_id = ?", (reservation_id,))
  82. conn.commit()
  83. print("Ticket cancelled successfully!")
  84. else:
  85. print("Reservation not found.")
  86.  
  87. # Function to display available trains
  88. def display_available_trains():
  89. print("\nAvailable Trains:")
  90. train.show_trains()
  91.  
  92. # Function to search for trains
  93. def search_trains_by_source_destination(source, destination):
  94. cursor.execute("SELECT * FROM trains WHERE source = ? AND destination = ?", (source, destination))
  95. rows = cursor.fetchall()
  96. if rows:
  97. for row in rows:
  98. print(f"Train ID: {row[0]}, Name: {row[1]}, Source: {row[2]}, Destination: {row[3]}, Departure: {row[4]}, Available Seats: {row[5]}")
  99. else:
  100. print("No trains found for this route.")
  101.  
  102. # Function to view reservations
  103. def view_reservations():
  104. cursor.execute("SELECT * FROM reservations")
  105. for row in cursor.fetchall():
  106. print(f"Reservation ID: {row[0]}, User: {row[1]}, Train ID: {row[2]}, Seat Count: {row[3]}, Status: {row[4]}")
  107.  
  108. # Sample Train Data
  109. train1 = Train("Express 101", "New York", "Boston", "2025-01-10 10:00", 50)
  110. train1.add_train()
  111.  
  112. train2 = Train("Express 102", "Los Angeles", "Chicago", "2025-01-12 09:00", 30)
  113. train2.add_train()
  114.  
  115. # Sample Reservation Data
  116. reservation1 = Reservation("John Doe", 1, 2)
  117. reservation1.book_ticket()
  118.  
  119. reservation2 = Reservation("Jane Smith", 2, 3)
  120. reservation2.book_ticket()
  121.  
  122. # Menu-driven interface
  123. def main():
  124. while True:
  125. print("\n--- Railway Management System ---")
  126. print("1. View Available Trains")
  127. print("2. Book Ticket")
  128. print("3. Cancel Ticket")
  129. print("4. Search Trains by Source and Destination")
  130. print("5. View All Reservations")
  131. print("6. Exit")
  132.  
  133. choice = int(input("Enter your choice: "))
  134.  
  135. if choice == 1:
  136. display_available_trains()
  137. elif choice == 2:
  138. user_name = input("Enter your name: ")
  139. train_id = int(input("Enter train ID: "))
  140. seat_count = int(input("Enter number of seats to book: "))
  141. reservation = Reservation(user_name, train_id, seat_count)
  142. reservation.book_ticket()
  143. elif choice == 3:
  144. reservation_id = int(input("Enter reservation ID to cancel: "))
  145. reservation = Reservation("", 0, 0)
  146. reservation.cancel_ticket(reservation_id)
  147. elif choice == 4:
  148. source = input("Enter source station: ")
  149. destination = input("Enter destination station: ")
  150. search_trains_by_source_destination(source, destination)
  151. elif choice == 5:
  152. view_reservations()
  153. elif choice == 6:
  154. print("Exiting system.")
  155. break
  156. else:
  157. print("Invalid choice, please try again.")
  158.  
  159. if __name__ == "__main__":
  160. main()
  161.  
  162. # Close the database connection at the end
  163. conn.close()
  164.  
Success #stdin #stdout 0.02s 25696KB
stdin
CREATE TABLE Train (
  TrainNum numeric PRIMARY KEY,
  TrainName varchar NOT NULL,
  Destination varchar NOT NULL,
  Source varchar NOT NULL,
  DisTravelled numeric Not NULL,
  NumOfCoaches numeric NOT NULL,
  Type varchar NOT NULL
  );
  
-- insert some values
INSERT INTO Train VALUES (1001, 'Malwa','Indore','Jammu',2500,1,'Superfast');
INSERT INTO Train VALUES (1002, 'Jammu Mail','Pune','Jammu',3500,12,'Superfast');
INSERT INTO Train VALUES (1003, 'Amritsar Exp','Amritsar','Delhi',900,08,'Local');
INSERT INTO Train VALUES (1004, 'Intercity Exp','Delhi','Bathinda',490,15,'Local');
INSERT INTO Train VALUES (1005, 'Samparak Kranti','Kerala','Ranchi',1500,13,'Superfast');
INSERT INTO Train VALUES (1006, 'Delhi Intercity','Delhi','Bhopal',7500,09,'Superfast');
INSERT INTO Train VALUES (1007, 'Rajdhani','Mumbai','Delhi',340,10,'Local');
INSERT INTO Train VALUES (1008, 'Avadh Assam','Assam','Agra',3600,07,'Superfast');
INSERT INTO Train VALUES (1009, 'Shatabdi','Delhi','Chandigarh',500,05,'Superfast');
INSERT INTO Train VALUES (1010, 'Jhelum','Mumbai','Jammu',3000,12,'Local');

stdout
import sqlite3

# Database connection
conn = sqlite3.connect('railway_management.db')
cursor = conn.cursor()

# Create tables for train and reservation data
cursor.execute("""
    CREATE TABLE IF NOT EXISTS trains (
        train_id INTEGER PRIMARY KEY AUTOINCREMENT,
        train_name TEXT,
        source TEXT,
        destination TEXT,
        departure_time TEXT,
        available_seats INTEGER
    )
""")

cursor.execute("""
    CREATE TABLE IF NOT EXISTS reservations (
        reservation_id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_name TEXT,
        train_id INTEGER,
        seat_count INTEGER,
        status TEXT,
        FOREIGN KEY (train_id) REFERENCES trains (train_id)
    )
""")
conn.commit()

# Class representing a train
class Train:
    def __init__(self, train_name, source, destination, departure_time, available_seats):
        self.train_name = train_name
        self.source = source
        self.destination = destination
        self.departure_time = departure_time
        self.available_seats = available_seats

    def add_train(self):
        cursor.execute("""
            INSERT INTO trains (train_name, source, destination, departure_time, available_seats)
            VALUES (?, ?, ?, ?, ?)
        """, (self.train_name, self.source, self.destination, self.departure_time, self.available_seats))
        conn.commit()

    def show_trains(self):
        cursor.execute("SELECT * FROM trains")
        for row in cursor.fetchall():
            print(f"Train ID: {row[0]}, Name: {row[1]}, Source: {row[2]}, Destination: {row[3]}, Departure: {row[4]}, Available Seats: {row[5]}")

# Class to manage reservations
class Reservation:
    def __init__(self, user_name, train_id, seat_count):
        self.user_name = user_name
        self.train_id = train_id
        self.seat_count = seat_count

    def book_ticket(self):
        cursor.execute("SELECT available_seats FROM trains WHERE train_id = ?", (self.train_id,))
        available_seats = cursor.fetchone()[0]

        if available_seats >= self.seat_count:
            cursor.execute("INSERT INTO reservations (user_name, train_id, seat_count, status) VALUES (?, ?, ?, ?)",
                           (self.user_name, self.train_id, self.seat_count, 'Booked'))
            cursor.execute("UPDATE trains SET available_seats = available_seats - ? WHERE train_id = ?",
                           (self.seat_count, self.train_id))
            conn.commit()
            print("Ticket booked successfully!")
        else:
            print("Not enough available seats.")

    def cancel_ticket(self, reservation_id):
        cursor.execute("SELECT seat_count, train_id FROM reservations WHERE reservation_id = ?", (reservation_id,))
        reservation = cursor.fetchone()

        if reservation:
            seat_count, train_id = reservation
            cursor.execute("UPDATE trains SET available_seats = available_seats + ? WHERE train_id = ?", 
                           (seat_count, train_id))
            cursor.execute("DELETE FROM reservations WHERE reservation_id = ?", (reservation_id,))
            conn.commit()
            print("Ticket cancelled successfully!")
        else:
            print("Reservation not found.")

# Function to display available trains
def display_available_trains():
    print("\nAvailable Trains:")
    train.show_trains()

# Function to search for trains
def search_trains_by_source_destination(source, destination):
    cursor.execute("SELECT * FROM trains WHERE source = ? AND destination = ?", (source, destination))
    rows = cursor.fetchall()
    if rows:
        for row in rows:
            print(f"Train ID: {row[0]}, Name: {row[1]}, Source: {row[2]}, Destination: {row[3]}, Departure: {row[4]}, Available Seats: {row[5]}")
    else:
        print("No trains found for this route.")

# Function to view reservations
def view_reservations():
    cursor.execute("SELECT * FROM reservations")
    for row in cursor.fetchall():
        print(f"Reservation ID: {row[0]}, User: {row[1]}, Train ID: {row[2]}, Seat Count: {row[3]}, Status: {row[4]}")

# Sample Train Data
train1 = Train("Express 101", "New York", "Boston", "2025-01-10 10:00", 50)
train1.add_train()

train2 = Train("Express 102", "Los Angeles", "Chicago", "2025-01-12 09:00", 30)
train2.add_train()

# Sample Reservation Data
reservation1 = Reservation("John Doe", 1, 2)
reservation1.book_ticket()

reservation2 = Reservation("Jane Smith", 2, 3)
reservation2.book_ticket()

# Menu-driven interface
def main():
    while True:
        print("\n--- Railway Management System ---")
        print("1. View Available Trains")
        print("2. Book Ticket")
        print("3. Cancel Ticket")
        print("4. Search Trains by Source and Destination")
        print("5. View All Reservations")
        print("6. Exit")
        
        choice = int(input("Enter your choice: "))
        
        if choice == 1:
            display_available_trains()
        elif choice == 2:
            user_name = input("Enter your name: ")
            train_id = int(input("Enter train ID: "))
            seat_count = int(input("Enter number of seats to book: "))
            reservation = Reservation(user_name, train_id, seat_count)
            reservation.book_ticket()
        elif choice == 3:
            reservation_id = int(input("Enter reservation ID to cancel: "))
            reservation = Reservation("", 0, 0)
            reservation.cancel_ticket(reservation_id)
        elif choice == 4:
            source = input("Enter source station: ")
            destination = input("Enter destination station: ")
            search_trains_by_source_destination(source, destination)
        elif choice == 5:
            view_reservations()
        elif choice == 6:
            print("Exiting system.")
            break
        else:
            print("Invalid choice, please try again.")

if __name__ == "__main__":
    main()

# Close the database connection at the end
conn.close()