0% found this document useful (0 votes)
5 views

cs project ir

Cs project

Uploaded by

nsurvase148
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

cs project ir

Cs project

Uploaded by

nsurvase148
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

INDEX

SL.NO CONTENT PAGE.NO


1. CERTIFICATE 2
2 ACKNOWLEDGEMENT 3
3 PROJECT TOPIC 4
4 INTRODUCTION 5
5 PROJECT DESCRIPTION 6-7
6 SOFTWARE & HARDWARE SPECIFICATION 8
7 DATA DICTIONARY (MAIN PROGRAM) 9
8 DATA DICTIONARY (DATABASE TABLES) 10
9 SOURCE CODES (SQL) 11-13
10 SOURCE CODES (PYTHON) 14-25
11 OUTPUTS 26-32
12 BIBLIOGRAPHY 33
CERTIFICATE

This to certify that, Akshath Pal, a student of


Class 12 A has successfully completed their
computer science project on the topic ‘RAILWAY
RESERVATIONS SYSTEMS’ under the guidance of
Mrs. Neelam Gupta in partial fulfillment of the
curriculum of Central Board of Secondary
Education leading to the award of annual
examination of the year.

> Internal Examiner :


> External Examiner :
2
ACKNOWLEDGEMENT

I would like to take this opportunity to express my


heartfelt gratitude to my Computer Science teacher,
Mrs. Neelam Guptafor providing her invaluable
guidance, support, and suggestions throughout the
course of the project. I owe my regards to our
respected principal-in-charge Mrs. Priyanka Gulati
for providing me with this golden opportunity. I
would also like to thank my parents and my friends,
whose aid was instrumental in helping me
accomplish my task within the time frame. The
project work has enhanced my knowledge and
helped me learn and evaluate many things.

3
RAILWAY
MANAGEMENT
SYSTEM

4
INTRODUCTION

The Railway Reservation System facilitates the passengers to enquire


about the trains available on the basis of source and destination,
Booking and Cancellation of tickets, enquire about the status of the
booked ticket, etc. The aim of the project is to design and develop a
database maintaining the records of different trains, train status, and
passengers.
This project is done by using Python as the programming language and
MySQL as the relational database management system. The database
contains three tables, the first one for storing all the train records, the
second one for storing the availability status of the trains, and the third
one for storing the passenger's list. A person can book the ticket by
providing some necessary information and then searching for the
available trains. Before booking the ticket, all the available trains are
shown, and a passenger has to choose. Then the ticket is booked and
the ticket PNR number (unique key of the ticket) is displayed. For
cancellation, a person can enter the PNR number and proceed to
cancel the ticket. The booked ticket can also be viewed by entering the
PNR number. The three tables can also be viewed by the help of this
program. The train table and the train seat availability table can also be
modified according to the needs with the help of this program.

5
PROJECT DESCRIPTION :
To explain briefly, this project will consist of these functionalities:
• Booking ticket: Users will be prompted to enter their name,
address, phone no, boarding station, destination station, and the
class they want to travel. Based on the boarding and destination
and the availability of seats in the requested class, the users will
be shown all the available trains and the fares. Then the user can
input the desired train no. and their ticket gets booked and the
unique PNR also gets displayed.
• Viewing ticket: Users can view their booked ticket by entering
their unique PNR of their ticket.
• Canceling ticket: Users can cancel their booked ticket by
entering their unique PNR of their ticket.
• Showing Customer Table: Users can view the details of all the
customers those who booked a ticket in this table.
• Showing Train Table: Users can view all the trains currently
running.
• Showing Train Seat Availability Table: Users. can view the
corresponding seat availability of all the classes of all the trains.
• Adding train in Train Table: Users can add a new train in the
existing train table.
• Removing train from train table: Users can remove a train from
the existing train table.
6
• Alter the Train Seat Availability Table: Users can change the
availability count of a particular class of a particular train.
Since the concept of railway reservation is much complex in reality,
some limitations has been considered:
• It is expected by the user to give fairly correct inputs as all the
possible incorrect test-cases has not been considered in the
project. • Only 6-7 trains are shown as
an example. • The train classes are limited to 6
(ACl/AC2/AC3ISL/CC/2S) • Date and time have not been
considered in train availability and booking to keep it simple.
• Only two types of train status,are considered: CONFIRMED and
CANCELLED.

7
SOFTWARE & HARDWARE
SPECIFICATION:

Hardware :
Processor - Intel® Core™ i3-2120 @ 3.30GHz
Installed RAM - 8 GB
Graphics - NVDIA GeForce GT 1030

Software :
Operation System - Windows 10 Pro
Programming Language - Python 3.10.5
Database Management - MySQL Community Server 8.0
IDE: Microsoft Visual Studio Cod (version 1.74)
8
DATA DICTIONARY:
MAIN PROGRAM:
Sl.
Name Type Description
No.
Used to connect the program with MySQL
1 mysql.connector module
Database

(here) used to display the relational tables in


2 pandas module
a structured manner

Function used to connect the python program


3 database_connect function
with the database

4 book_ticket function Function used to book the ticket

5 cancel_ticket function Function used to cancel the ticket

6 show_ticket function Function used to show the ticket

7 show_trainDB function Function used to show train table

8 show_customerDB function Function used to show the customer table

Function used to show train seat availability


9 show_availDB function
table

10 add_train function Function used to add train to train table

Function used to remove train from train


11 remove_train function
table

Function used to alter the seat availability of


12 change_seat_avail function
a train in Train seat availability table

Used to store the name of the working


13 DATABASE variable
database.

14 con variable Used to store the database connection

15 cur variable Used to store the database cursor object

Used to store the desired option entered by


16 key variable
the user in menu
9

DATABASE TABLES:
10

SOURCE CODE:
SQL CODES :
DROP DATABASE IF EXISTS railway;

CREATE DATABASE railway;

USE railway;

CREATE TABLE train_table(

trno varchar(5) unique not null,

trname varchar(60) unique not null.

stoppage json not null,

¢lass json not null,

PRIMARY KEY(trno)

);

CREATE TABLE avail_table(

trno varchar(5} not null,

AC1 integer default 0,

AC2 integer default 0,

AC3 integer default 0,

SL integer default 0,

CC integer default 0,

2S integer default 0,

foreign key (trno) references train_table(trno)

);
CREATE TABLE customer_table(
pnr integer not null auto_increment,
trno varchar(5) not null,

11
cust_name varchar(60) not null,

cust_addr varchar(150) ,

cust_ph varchar(15),

boarding varchar(60) not null,

destination varchar(60) not null,

class varchar(10) not null,

n_seats integer not null,

price integer not null,

stats varchar(10) not null,

foreign key (trno) references train.table(trno),

PRIMARY KEY (pnr)

);

ALTER TABLE customer_table AUTO_INCREMENT= 10000001;

INSERT INTO train_table


VALUES.

("12041", "HwH NIP SHATABDI EXPRESS", ’[“howrah”,


“bolpur” ,“farakka”,"malda”,"barsol” ,"kishanganj”, “new Jalpaiguri"]’ , ‘["cc"]’),

(" 12042", “NJP HWH SHATABDI EXPRESS", ' ["new


jalpaiguri”,"kishanganj” ,“barsol","malda","farakka”,“bolpur”, “howrah”]’ , ‘[“CC”]’),

(“12035", "SDAH NDLS RAJDHANI EXPRESS”, ‘["sealdah", “durgapur" ,"asansol” ,


“dhanbad”, “gaya” , “dd upadhyaya” , "kanpur central", "new delhi"]’,’
["AC3".“AC2"."ACI"]’)

(“12036", “NDLS SDAH RAJDHANI EXPRESS", ‘["new delhi". “kanpur cantral” “dd
upadhyaya”, "gaya" ,“dhanbad" ,"durgapur","sealdah”)’,’["AC3", "AC2",”AC 1”]’),
(“22387". “HWH DHN BLACKDIAMOND EXPRESS",‘("howrah” ,"seoraphuli”, “bandel”,
“barddhaman" ,"“mankar”
“panagarh",."durgapur” ,"waria”,”andal" ,“raniganj”,“asansol” ,“sitarampur”,"kulti",
”barakar”,"kumardubi”,“dhanbad"]' , '["CC" "25"]' ),

12

(“22388", “DHN HWH BLACKDIAMOND EXPRESS",’["dhanbad”, "kumardubi",


“barakar" , "kulti”, "sitarampur", ”asansol”, ”raniganj”, "andal","waria”, "durgapur”,
“panagarh" , "mankar", "barddhaman”,“bandel","seoraphuli","howrah’]’,
’["CC","25"]' );

INSERT INTO avail_table

VALUES

("12041" ,0,0,0,0,200,0),

("12042",0,0,0,0,200,0),

("12035",100,100,100,0,0,0),

("12036" ,100, 100, 100,0,0.0),

("22387" ,0,0,0,0,200,200),

(“22388" ,0,0,0,0,200,200);
13

PYTHON CODES :
import mysql.connector as sql import pandas as pd
pd. set_option( 'display.max_rows', None) pd.
set_option( 'display.width’, 2000) pd.
set_option( 'display.max_columns’, None)

DATABASE = "railway" FARE ={"AC1" :15000, "AC2":


1200, “AC3”: 1000, “SL” :500, "CC": 800, "25": 400)

def database_connect (host, username, password, db_name) :

print("Connecting to database...")

connection = sql.connect (host=host,


user=username, password=password, database=db_name)

if connection, is_connected():
print("Successfully connected to the database“)
cursor = connection. cursor() return connection,
cursor

else: print("Failed to connect


the database”) return None, None

def book_ticket(db_con,.db_cursor):

try: print()
name = input("Enter your name: ") addr
= input("Enter your address: “) ph_no = input(“Enter your
phone number: “) boarding = input(“Enter your boarding station:
"). lower() dest = input("Enter your destination station: "). lower()
tr_class = input("Enter the train class you want to travel (ACI/AC2/AC3/SL/00/25) :
“).upper ()

n_seats = int(input("Enter no of seats you want to book: "))


db_cursor.execute(f"SELECT * FROM train_table:”)
14
all_trains = db_cursor. fetchall()
avail_trains - []

if db_cursor. rowcount>0:

for i in all_trains:
stoppage = eval(i(2]) if boarding in stoppage and dest in
stoppage:

If stoppage. index (boarding)


<stoppage index (dest);

db_cursor.execute(f"SELECT {tr_class} FROM


avail_table WHERE trno={i [0] }")
avail_seats = db_cursor.fetchone() [0] if avail_seats>=n_seats:
avail_trains.append(i)

if len(avail_trains)>0:

for i in range(len(avail_trains)):

print(f"\nFare for each seats in {trlass}


class : Rs.{FARE[triclass]}")

print("\nAvailable Trains...")

print(f’{i+1}.")

print(f"Train No.: {avail_trains([i](O]}\nTrain

Name: {avail_trains[i][1]}")

booked_tr = input("Enter the train no. you wish to

choose: “)

if booked_tr in [i[0) for i in avail_trains]:

price = n_seats*FARE[tr_class]
15
db_cursor.execute(f” INSERT INTO
customer_table(trno, cust_name, cust_addr , cust_ph, boarding, destination,
class ,n_seats, price, stats) VALUES (\“
{booked_tr}\",\"{name}\" ,\"{addr}\", \"{ph_no}\" ,\"{boarding}\", \"
{dest}\" ,\"{tr_class}\" , {n_seats}, {price}, \"CONFIRMED\" ) ” )

db_con. commit ()

db_cursor.execute(f"SELECT {tr_class} FROM


avail_table WHERE trno={booked_tr}")
avail_seats = db_cursor.fetchone() [0]

db_cursor.execute(f"UPDATE avail_table SET


{tr_class}={avail_seats-n_seats} WHERE trno=\"{booked_tr}\";")

db_con. commi t()

db_cursor.execute(f"SELECT pnr FROM customer_table ORDER BY


pnr”)

pnr = db_cursor. fetchall() [db_cursor. rowcount-

1] [0]

print("Ticket Booked Successfully!")

printC'Ticket PNR No.",pnr) ~

else:

print(f"\nSorry! No trains with the train no.

‘{booked_tr}' are available for now!")

else:

print("\nSorry! No trains available for now!")

else:

print("\nSorry! No trains available for now!")


16

except:

print(“Please check your inputs and try again!”)

def cancel_ticket(db_con,db_cursor):
print()
pnr = input("Enter your PNR Number: “)
try:

db_cursor.execute(f"SELECT * FROM customer_table WHERE pnr={pnr}")

ticket = db_cursor. Fetchall()

if db_cursor. rowcount>0:

db_cursor.execute(f’ SELECT trname FROM train_table WHERE

trno=\" {ticket [0] [1]}\"")

train = db_cursor. fetchone() [0]


print("\nTicket Details:")
print("PNR:" ,ticket(0] [0])
print("Customer Name: ",ticket [0][2])
print("Train : ”, ticket[0][1], train)
print(“Boarding:", ticket [0] [5] .upper())
print("Destination:”,ticket[0] [6] .upper())
print("Class:", ticket [0][7])
print("No. of Seats:”,ticket[0][8])
print("Status:”,ticket[0][10])

cancel = input("\nDo you want to cancel your ticket?(Y/N): “).upper()


if cancel in ["Y","YES"]:
db_cursor.execute(f"UPDATE customer_table SET stats
= \"CANCELLED\" WHERE pnr = {ticket[0][0]}")

db_cursor.execute(f"SELECT {ticket[0][7]} FROM avail_table WHERE


trno={ticket[0][1]}")

avail_seats = db_cursor. fetchone()[0]


db_cursor.execute(f" UPDATE avail_table SET {ticket [0]
[7] }={avail_seats+ticket[0][8]} WHERE trno=\" {ticket [0][1]}\";")
17

db_con. commit ()

print(“Ticket successfully cancelled!")

else:

print(’Ticket not cancelled!"}

else:

print("Invalid PNR Number!"')

except:

print("Invalid PNR Number!'')

def show_ticket(db_cursor):

print() pnr =
input("Enter your PNR Number: ")

try:

db_cursor.execute(f"SELECT * FROM customer_table WHERE pnr={pnr}")

ticket = db_cursor.fetchal1()

if db_cursor. rowcount>0:

db_cursor.execute(f"SELECT trname FROM train_table WHERE


trno=\"{ticket[0][1] }\"")

train = db_cursor. fetchone() [0] print("\


n----------------Ticket Detai]s-----------------")
print(“Customer Name:",ticket([0][2])
print("Customer Address:",ticket[0][3])
print("Customer Phone No.". ticket[0][4]) print()

18
print(’PNR:”,ticket[0][0])
print(“Train:", ticket [0] [1], train)
print (“Boarding:”, ticket [0] [5].upper())
print("Destination:", ticket [0] [6] .upper())
print("Class:", ticket [0][7])
print("No. of Seats:", ticket [0][8])
print(“Status:”, ticket[0][10])
print(“Amount Paid:",ticket[0][9])
print(“-----------------------------------------------------------------------")

else:

print("Invalid PNR Number!”)

except:

print("Invalid PNR Number!")

def show_trainDB(db_cursor):

try:

db_cursor.execute("SELECT * FROM train_table”)


all_trains = db_cursor.fetchall()

output_df = pd.DataFrame(all_trains, columns=["Train No.”, "Train Name",


“Stoppages", “Classes"])

output_df.index+=1

print()

print(output_df)

except:

print("Some error occured! Please try again.")

19
def show_customerDB(db_cursor):

try:

db_cursor.execute("SELECT * FROM customer_table")


all_customers = db_cursor.fetchall()
output_df = pd.DataFrame(all_customers, columms=["PNR”, “Train No.",
“Name”, “Address”, “Phone No.", “Boarding”, “Destination”, "Class", "No. of
Seats", "Fare", "Status"])

output_df. index+=1
print()
print(output_df)

except:

print(“Some error occured! Please try again.")

def show_availDB(db_cursor):

try:

db_cursor.execute(“SELECT * FROM avail_table")


all_trains = db_cursor.fetchall()
output_df = pd.DataFrame(all_trains, columns=[“Train No.”. "ACI", "AC2",
"ACI", "SL", "CC", "2S"])
output_df.index+=1
print()
print (output_df)

except :
print("Some error occured! Please try again!")

def add_train(db_con,db_cursor):
try:

print()
trno = input("Train no. : “)

20
if len(trno)!=5 and not trno.isnumeric():
print("Train No. is not valid!")
return None
trname = input("Train Name: "). upper()

N=int(input(“No. Of stoppages :”))


print(“Enter the stoppages one by one :”)
stoppage=[] for i in
range(n):
stoppage.append(input().lower())

n=int(input(“No of classes available:”))

print(“Enter the classes available and the available seats one by one:”)

classes={}

for i in range(n):

n_class=input().upper().split()

If n_class [0].upper() in [“ACI”, "AC2", "AC1", "SL", "CC", "2S"]:

classes [n_class[0].upper()]=int(n_class[1])

else :

print( f” ‘(n_class[0].upper()} ’class does ont exist!”)

return none

stoppage_str=str(stoppage).replace(“\’ “,”\””)
class_str = str(list(classes.keys())).replace(“\ ‘ “,”\””)

db_cursor.execute(f”INSERT INTO train_tables VALUES (\”{trno}\”,


\”{trname}\” ,\’{stoppage_str}\’, \’{class_str}\’)”)

db_cursor.execute(f”INSERT INTO avail_table(trno,{‘,’.join(classes.keys()))})


VALUES ({trno}, {‘,’.join[str (i) for i in classes.values()])})”)

db_con.commit()

print(“Train added succesfully!”)

21
except :
print(“Some error occured! Please try again!")

def remove_train(db_con , db_cursor):

try:

print()
db_cursor.execute(f”SELECT trno FROM train_table”)
all_trains = [I[0] for i = db_cursor.fetchall()]
trno = input(“Enter the train no. of the train you want to remove :”)

if trno not in all_trains:


print(“Train no. not found in the database”)
return None

db_cursor.execute(f”SELECT*FROM train_table WHERE trno=\”{trno}\””)

tr_details = db_cursor.fetchone()
print(“Train Details:”)
print(“Train Name:”,tr_details[1])
print(“Train Stoppages:”,”,”.join(eval (tr_details[2])))
print(“Available Classes:”,”,”.join(eval (tr_details[3])))

remove = input("\nDo you want to delete this train record from


the table? (Y/N): ").upper()

if remove in ["Y",”YES"]:

db_cursor.execute(f"DELETE FROM avail_table WHERE


trno=\"(trno}\"")
db_con. commit()

db_cursor.execute(f"DELETE FROM train_table WHERE


trno=\"{trno}\"")

db_con. commit() print(“Train deleted from


Train Table successfully!")

22
else:

print("Train not deleted.")

except:

print("Some error occured! Please try again.”)

def change_seat_avai 1(db_con, db_cursor):

try:

print() trno = input(“Enter the train no: ")


db_cursor.execute(f"SELECT trno
FROM train_table”) all_trains = [i[0] for i in db_cursor.
fetchall()] if trno in all_trains:

db_cursor.execute(f"SELECT class FROM train_table WHERE


trno=\"(trno}\"")

avail_classes = db_cursor. fetchone() [0]


tr_class = input("Enter the class (AC1/AC2/AC3/SL/CC/25) for which you
want to change the availibility: ") .upper()

if tr_class in avail_classes:
db_cursor.execute(f"SELECT {tr_class} FROM avail_table WHERE
trno=\"{trno}\"")

prev_count = db_cursor.fetchone()[0]
print(’Prev. available no. of seats:",prev_count)
new_count = input("Enter the new no. of seats: “) if
new_count.isnumeric():

db_cursor.execute(f"UPDATE avail_table SET {tr_class}=


{new_count} WHERE trno = \"{trno}\"")

db_con. commit()
print("\nUpdated successfully!")

23
else:
print("Invalid input!”)

else:
print("This class is not present in this train.”)

else:

print("Train does not exist in the train table.")

except:

print("Some error occured! Please try again!")

print(“Loading...")
con,cur = database_connect (“localhoast’, “root”, “mypass” , DATABASE)
print (“Successfully Loaded... \n\n")

print (“===================================RAILWAY MANAGEMENT


SYSTEM==================================")

while True:
print(f'\n\n{'-'*30}")
print("MENU:")
print("Enter 1 to Book Ticket")
print("Enter 2 to View Ticket")
print("Enter 3 to Cancel Ticket")
print(“Enter 4 to View Customer Table")
print("Enter 5 to View Train Table")
print("Enter 6 to View Train Seat Availability Table")
print(“Enter 7 to Add Train in Train Table")
print("Enter 8 to Remove Train from Train Table")
print("Enter 9 to Make Changes in Train Seat Availability Table")
print("Press E to Exit")

key = input("\nEnter your desired option: “)

24
if key=='1':
book_ticket(con, cur)
elif key=='2':
show_ticket (cur) elif
key=='3':
cancel_ticket(con, cur) elif
key=='4':
show_customerDB (cur) elif
key=='5":
show_trainDB(cur) elif. Key==’6’:
show_avaiIDB
(cur)

25
OUTPUT:
STARTING AND MENU PAGE :

BOOK A TICKET :

26
VIEW A TICKET :

CANCEL A TICKET :

27
BOOK TWO MORE TICKETS :

SHOWING CUSTOMER TICKET :

28
SHOWING TRAIN TABLE :

SHOWING TRAIN SEAT AVAILABILITY TABLE :

29
ADDING TRAIN IN TRAIN TABLE :

CHECKING IF TRAIN IS ADDED OR NOT :

30
UPDATING AVAILABILITY OF SEATS TRAIN TABLE :

CHECKING IF CHANGES ARE REFLECTED ON AVAILABILITY TABLE :

31
EXITING APPLICATION :

32
BIBLIOGRAPHY :

SITES:
1. www.geeksforgeeks.org
2. www.w3schools.com
3. www.stackoverflow.com
4. www.github.com
5. https://docs.python.org/
6. https://dev.mysql.com/doc/

BOOKS:
1. Computer Science with Python Textbook Class XII
2. NCERT Computer Science Class XII

_____________

33

You might also like