Cinema Tickets – MySQL Python

This project is based on Python-MySQL database connectivity and has a Character User Interface. Create the files dbcon.py, modules.py and interface .py and copy the code. The MySQL database has user ‘root’ and blank password. This project is for students of class XII and not a professionally designed product.

dbcon.py

def dbcon():
    # Initial Script to create database schema
    import mysql.connector as myc

    try:
        con = myc.connect(host='localhost',user='root',passwd='')
        mycursor = con.cursor()
        mycursor.execute('DROP DATABASE IF EXISTS cinemaproj')
        mycursor.execute('CREATE DATABASE cinemaproj')
        mycursor.execute('USE cinemaproj')
        mycursor.execute('DROP TABLE IF EXISTS hall_det')
        sql = '''CREATE TABLE hall_det(
                    hallno INT(5) NOT NULL AUTO_INCREMENT,
                    hallname VARCHAR(20) NOT NULL,
                    frontseats INT(3) NOT NULL,
                    midseats INT(3) NOT NULL,
                    backseats INT(3) NOT NULL,
                    CONSTRAINT hall_pk PRIMARY KEY(hallno))'''
        mycursor.execute(sql)
        mycursor.execute('ALTER TABLE hall_det AUTO_INCREMENT = 1000')
        mycursor.execute('DROP TABLE IF EXISTS booking_det')
        sql = '''CREATE TABLE booking_det(
                    tickectno INT(6) NOT NULL AUTO_INCREMENT,
                    hallno INT(5) NOT NULL,
                    customer VARCHAR(15) NOT NULL,
                    no_of_seats INT(2) NOT NULL,
                    cost_of_seat INT(4) NOT NULL,
                    seattype CHAR(1) NOT NULL,
                    discount INT(3) NULL,
                    CONSTRAINT ticket_pk PRIMARY KEY(tickectno),
                    CONSTRAINT h_fk FOREIGN KEY(hallno) 
                    REFERENCES hall_det(hallno))'''
        mycursor.execute(sql)
        mycursor.execute('ALTER TABLE booking_det AUTO_INCREMENT = 10000')
        #Inserting Rows in to the Cinema hall table
        sql = """INSERT INTO hall_det(hallname, frontseats, midseats,backseats)
        VALUES(%s, %s, %s, %s)"""
        rows = [('PVR-YPR',50,50,50),('INOX-MANTRI',50,50,50),\
        ('PVR-GOP',50,50,50),('PHOENIX',60,50,50)]
        mycursor.executemany(sql, rows)
        con.commit()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        print('Database schema Creatred')
        con.close()

module.py

#Function to retuen the number of seats available in a hall
def getseats(hno):
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT frontseats, midseats, backseats FROM hall_det WHERE hallno='%d'" % (hno)
        mycursor.execute(sql)
        rec = mycursor.fetchone()
        con.close()
    except myc.Error as err:
        print(err)
    finally:
        return rec

#Function to get all the hall numbers
def hallnums():
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT hallno FROM hall_det ORDER BY hallno"
        mycursor.execute(sql)
        rec = mycursor.fetchall()
        hlst =[]
        for x in rec:
            hlst.append(x[0])
    except myc.Error as err:
        print(err)
    finally:
        con.close()
        return hlst

#Function to get all ticket numbers
def getticketdet():
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT tickectno FROM booking_det"
        mycursor.execute(sql)
        rec = mycursor.fetchall()
        tlst =[]
        for x in rec:
            tlst.append(x[0])
    except myc.Error as err:
        print(err)
    finally:
        con.close()
        return tlst

#Function to update the seats based on bookings
def updateseats(hno,stype,amt):
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        if stype=='A':
            sql = "UPDATE hall_det SET frontseats=frontseats-'%d' WHERE hallno='%d'" % (amt,hno)
        if stype=='B':
            sql = "UPDATE hall_det SET midseats=midseats-'%d' WHERE hallno='%d'" % (amt,hno)
        if stype=='C':
            sql = "UPDATE hall_det SET backseats=backseats-'%d' WHERE hallno='%d'" % (amt,hno)
        mycursor.execute(sql)
        con.commit()    
    except myc.Error as err:
        print(err)
    finally:
        print('Seats updated')
        con.close()
    
#Function to book the seats and also call update seats function     
def booking(hno, cname,noseat, cost,stype, disc=0):
    import mysql.connector as myc
    s1,s2,s3=getseats(hno)
    if (stype=='A' and noseat>s1) or (stype=='B' and noseat>s2) or (stype=='C' and noseat>s3):
        return 'No seats available'
    else:
        try:
            con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
            mycursor=con.cursor()
            sql="INSERT INTO booking_det(hallno,customer,no_of_seats,cost_of_seat,seattype, discount) \
            VALUES(%s,%s,%s,%s,%s,%s)" 
            rows=[(hno, cname,noseat, cost,stype, disc)]
            mycursor.executemany(sql,rows)
            con.commit()
            #update the seats after booking
            updateseats(hno,stype,noseat)                
        except myc.Error as err:
            print(err)
        finally:
            print('Record Inserted')
            con.close()     
#booking(101,1001,'Ashok',4,500,'A',0)  

#Function to display booking details for a given hall
def showhallbooking(hno):
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT b.tickectno, b.hallno, h.hallname, b.seattype, b.no_of_seats, b.cost_of_seat, b.discount\
        FROM booking_det b, hall_det h WHERE b.hallno=h.hallno and b.hallno='%d'" % (hno)
        mycursor.execute(sql)
        rec = mycursor.fetchall()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        con.close()
        return rec
#print(showhallbooking(1001))

#Function to print the hall status
def hallstat():
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT hallno, hallname,frontseats, midseats, backseats FROM hall_det" 
        mycursor.execute(sql)
        rec = mycursor.fetchall()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        con.close()
        return rec
#print(hallstat())  
#function to display all bookings
def allbookings():
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT b.tickectno, h.hallno, h.hallname, b.seattype, b.no_of_seats, b.cost_of_seat, b.discount,\
        h.frontseats, h.midseats, h.backseats FROM booking_det b, hall_det h WHERE b.hallno=h.hallno"
        mycursor.execute(sql)
        rec = mycursor.fetchall()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        con.close()
        return rec
#print(allbookings())

def addhall(hname, fs,ms,bs):
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql="INSERT INTO hall_det(hallname, frontseats, midseats, backseats) VALUES(%s,%s,%s,%s)" 
        rows=[(hname,fs,ms,bs)]
        mycursor.executemany(sql,rows)
        con.commit()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        print('Hall added')
        con.close()
#addhall(1005,'VAISHNAVI-SAPPHIRE', 100,100,100) 

def printticket(tno):
    
    try:
        import mysql.connector as myc
        con = myc.connect(host='localhost',user='root',passwd='', database='cinemaproj')
        mycursor=con.cursor()
        sql = "SELECT b.tickectno, b.hallno, h.hallname, b.customer,b.seattype, b.no_of_seats, b.cost_of_seat, b.discount\
        FROM booking_det b, hall_det h WHERE b.hallno=h.hallno and b.tickectno='%d'" % (tno)
        mycursor.execute(sql)
        rec = mycursor.fetchall()
    except myc.Error as err:
        print(err)
        print("SQLSTATE", err.sqlstate)
    finally:
        con.close()
        return rec
#print(printticket(101))  

#Function to enforce integer input. Use this while accepting integers
def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break  
    

interface.py (Run this file to run the project)

import dbinit as d
import modules as m
import os, sys

while True:

    print('||==============Book My Show===================||')
    print('||      You can perform the following tasks    ||')
    print('|| Type 0 to reset Application                 ||')
    print('|| Type 1 to add a hall in your portal         ||')
    print('|| Type 2 to view all the halls in your portal ||')
    print('|| Type 3 to see the booking status of a hall  ||')
    print('|| Type 4 to book a ticket in a hall           ||')
    print('|| Type 6 to see booking of all the halls      ||')
    print('|| Type 7 to generate ticket for booking       ||')
    print('|| Type 8 to quit                              ||')
    print('||=============================================||')
    choice=m.inputNumber('Enter your choice:')
    if choice==0:
        d.dbcon()
    if choice == 1:
        hname=input('Enter your hall name:')
        fs = m.inputNumber('Enter the maximum front seats:')
        ms = m.inputNumber('Enter the maximum middle seats:')
        bs = m.inputNumber('Enter the maximum back seats:')
        m.addhall(hname,fs,ms,bs)
    if choice==2:
        import pandas as pd
        rec =m.hallstat()
        df = pd.DataFrame(rec)
        df.columns= ['Hall No', 'Hall Name', 'A-Type', 'B-Type', 'C-Type']
        print(df)
    if choice==4:
        import pandas as pd
        print('You have the following hall Numbers')
        print(m.hallnums())
        hno=m.inputNumber('Enter a valid hallno:')
        cname=input('Enter Customer name:')
        stype=input('Enter Seat Type as A,B,C:')
        noseat=m.inputNumber('Enter numbner of seats:')
        cost = m.inputNumber('Enter cost of each seat:')
        dis=0
        if noseat*cost>=2000:
            dis=100
        m.booking(hno,cname,noseat,cost,stype,dis)
    if choice==3:
        import pandas as pd
        print('You can get details of the following hall Numbers')
        print(m.hallnums())
        hno=m.inputNumber('Enter a valid hallno:')
        if hno in m.hallnums():
            rec = m.showhallbooking(hno)
            df=pd.DataFrame(rec)
            df.columns = ['Hall No','Ticket No','Hall Name','Seat Type','No of Seate','Rate','Discount']
            print(df)
        else:
            print('Invalid Hall Number')
    if choice==6:
        import pandas as pd
        rec = m.allbookings()
        df=pd.DataFrame(rec)
        df.columns=['Hall No','Ticket NO','Hall Name','Seat Type','No of Seats',\
        'Cost per seat','Discount','A-Type','B-Type','C-Type']
        print(df)
    if choice==7:
        tno = m.inputNumber('Enter the ticket number:')
        rec = m.getticketdet()
        if tno in rec:
            rec = m.printticket(tno)
            print("---------Ticket Details-----------")
            print("Ticket Number is   :%d" % (rec[0][0]))
            print("Hall Number is     :%d" % (rec[0][1]))
            print("Hall Name          :%s" % (rec[0][2]))
            print('Customer name is   :%s' % (rec[0][3]))
            print('Seat Type          :%s' % (rec[0][4]))
            print("Number of Seats    :%d" % (rec[0][5]))
            print("Cost per Seat      :%d" % (rec[0][6]))
            print("Discount           :%d" % (rec[0][7]))
            total = rec[0][5]*rec[0][6]-rec[0][7]
            print("Total Cost         :%d" % (total))
            #print(rec)
        else:
            print('Ticket Number not available')

    if choice==8:
        sys.exit(0)
    

    os.system('pause')
    os.system('cls')

Just another Ashoksquest.org Initiativs site