0% found this document useful (0 votes)
10 views16 pages

Parking

Parking

Uploaded by

saiprasadp47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Parking

Parking

Uploaded by

saiprasadp47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Python

import mysql.connector #password - password123 user-admin

from mysql.connector import Error

from datetime import datetime

def connect_to_db():

try:

connection = mysql.connector.connect(

host="localhost",

user="root",

password="1234", # Replace with your MySQL password

database="ParkingDB" # Ensure the database exists

if connection.is_connected():

return connection

except Error as e:

print(f"Error connecting to database: {e}")

return None

# Add Parking Slots

def add_parking_slots():

db = connect_to_db()

cursor = db.cursor()

num_slots = int(input("Enter the number of parking slots to add: "))

for _ in range(num_slots):

cursor.execute("INSERT INTO ParkingSlots (IsOccupied) VALUES (FALSE)")

db.commit()

print(f"{num_slots} parking slots added successfully.")


db.close()

# Check In Vehicle

def check_in_vehicle():

db = connect_to_db()

if db is None:

print("Database connection failed. Please try again later.")

return

try:

cursor = db.cursor()

vehicle_number = input("Enter vehicle number: ").strip()

vehicle_type = input("Enter vehicle type (Car/Bike/Truck): ").strip()

# Validate vehicle type

if vehicle_type.lower() not in ["car", "bike", "truck"]:

print("Invalid vehicle type. Please enter 'Car', 'Bike', or 'Truck'.")

return

# Check for an available slot

cursor.execute("SELECT SlotID FROM ParkingSlots WHERE IsOccupied = FALSE LIMIT 1")

slot = cursor.fetchone()

if slot:

slot_id = slot[0]

entry_time = datetime.now()

cursor.execute("""

UPDATE ParkingSlots

SET VehicleNumber = %s, VehicleType = %s, EntryTime = %s, IsOccupied = TRUE


WHERE SlotID = %s

""", (vehicle_number, vehicle_type, entry_time, slot_id))

db.commit()

print(f"Vehicle checked in successfully. Slot ID: {slot_id}")

else:

print("No available slots.")

except Error as e:

print(f"Error during vehicle check-in: {e}")

finally:

db.close()

def calculate_fee(vehicle_type, duration_hours):

if vehicle_type.lower() == "car":

return duration_hours * 10 # Example: $10/hour for cars

elif vehicle_type.lower() == "bike":

return duration_hours * 5 # Example: $5/hour for bikes

elif vehicle_type.lower() == "truck":

return duration_hours * 20 # Example: $20/hour for trucks

else:

return duration_hours * 15 # Default fee

def check_out_vehicle():

db = connect_to_db()

cursor = db.cursor()

vehicle_number = input("Enter vehicle number: ")

cursor.execute("SELECT SlotID, VehicleType, EntryTime FROM ParkingSlots WHERE VehicleNumber


= %s AND IsOccupied = TRUE", (vehicle_number,))

slot = cursor.fetchone()

if slot:
slot_id, vehicle_type, entry_time = slot

exit_time = datetime.now()

duration = (exit_time - entry_time).total_seconds() / 3600 # Duration in hours

fee = calculate_fee(vehicle_type, duration)

cursor.execute("""

UPDATE ParkingSlots

SET VehicleNumber = NULL, VehicleType = NULL, EntryTime = NULL, ExitTime = NULL,


IsOccupied = FALSE, Fee = %s

WHERE SlotID = %s

""", (fee, slot_id))

db.commit()

print(f"Vehicle checked out. Slot ID: {slot_id}, Duration: {duration:.2f} hours, Fee: ${fee:.2f}")

else:

print("Vehicle not found in the parking lot.")

db.close()

# View Parking Lot Status

def view_parking_status():

db = connect_to_db()

if db is None:

print("Database connection failed. Please try again later.")

return

try:

cursor = db.cursor()

cursor.execute("SELECT * FROM ParkingSlots")

rows = cursor.fetchall()

if rows:
print("SlotID | VehicleNumber | VehicleType | EntryTime | ExitTime | IsOccupied")

for row in rows:

print(f"{row[0]} | {row[1] or 'None'} | {row[2] or 'None'} | {row[3] or 'None'} |


{row[4] or 'None'} | {row[5]}")

else:

print("No parking slots found.")

except Error as e:

print(f"Error retrieving parking status: {e}")

finally:

db.close()

def reserve_slot():

db = connect_to_db()

cursor = db.cursor()

cursor.execute("SELECT SlotID FROM ParkingSlots WHERE IsOccupied = FALSE AND Reserved =


FALSE LIMIT 1")

slot = cursor.fetchone()

if slot:

slot_id = slot[0]

cursor.execute("UPDATE ParkingSlots SET Reserved = TRUE WHERE SlotID = %s", (slot_id,))

db.commit()

print(f"Slot {slot_id} has been reserved successfully.")

else:

print("No available slots for reservation.")

db.close()

def slot_utilization_report():

db = connect_to_db()

cursor = db.cursor()
cursor.execute("""

SELECT SlotID, COUNT(*) AS UsageCount

FROM ParkingSlots

WHERE EntryTime IS NOT NULL

GROUP BY SlotID

ORDER BY UsageCount DESC

""")

rows = cursor.fetchall()

print("SlotID | Usage Count")

for row in rows:

print(f"{row[0]} | {row[1]}")

db.close()

def view_daily_revenue():

db = connect_to_db()

if db is None:

print("Database connection failed. Please try again later.")

return

try:

cursor = db.cursor()

cursor.execute("""

SELECT DATE(ExitTime) AS Date, SUM(Fee) AS TotalRevenue

FROM ParkingSlots

WHERE ExitTime IS NOT NULL

GROUP BY DATE(ExitTime)

""")

rows = cursor.fetchall()

if rows:
print("Date | Total Revenue")

for row in rows:

print(f"{row[0]} | ${row[1]:.2f}")

else:

print("No revenue records found.")

except Error as e:

print(f"Error generating daily revenue: {e}")

finally:

db.close()

def search_vehicle():

db = connect_to_db()

cursor = db.cursor()

vehicle_number = input("Enter vehicle number to search: ")

cursor.execute("""

SELECT SlotID, VehicleType, EntryTime, IsOccupied

FROM ParkingSlots

WHERE VehicleNumber = %s

""", (vehicle_number,))

vehicle = cursor.fetchone()

if vehicle:

slot_id, vehicle_type, entry_time, is_occupied = vehicle

status = "Occupied" if is_occupied else "Vacant"

print(f"Vehicle Found: Slot ID: {slot_id}, Type: {vehicle_type}, Entry Time: {entry_time}, Status:
{status}")

else:

print("Vehicle not found in the parking lot.")

db.close()
def admin_login():

db = connect_to_db()

cursor = db.cursor()

username = input("Enter username: ")

password = input("Enter password: ")

cursor.execute("SELECT * FROM Admins WHERE Username = %s AND Password = %s", (username,


password))

admin = cursor.fetchone()

if admin:

print("Login successful!")

return True

else:

print("Invalid credentials.")

return False

def display_parking_availability():

db = connect_to_db()

cursor = db.cursor()

cursor.execute("SELECT COUNT(*) FROM ParkingSlots WHERE IsOccupied = FALSE")

available_slots = cursor.fetchone()[0]

cursor.execute("SELECT COUNT(*) FROM ParkingSlots WHERE IsOccupied = TRUE")

occupied_slots = cursor.fetchone()[0]

print(f"Available Slots: {available_slots}")

print(f"Occupied Slots: {occupied_slots}")

db.close()
def register_customer():

db = connect_to_db()

cursor = db.cursor()

name = input("Enter customer name: ")

phone = input("Enter customer phone: ")

vehicle_number = input("Enter vehicle number: ")

try:

cursor.execute("""

INSERT INTO Customers (Name, Phone, VehicleNumber)

VALUES (%s, %s, %s)

""", (name, phone, vehicle_number))

db.commit()

print("Customer registered successfully.")

except mysql.connector.Error as err:

print(f"Error: {err}")

db.close()

def view_customers():

db = connect_to_db()

cursor = db.cursor()

cursor.execute("SELECT * FROM Customers")

rows = cursor.fetchall()

print("CustomerID | Name | Phone | VehicleNumber")

for row in rows:

print(f"{row[0]} | {row[1]} | {row[2]} | {row[3]}")

db.close()
def advanced_search():

db = connect_to_db()

cursor = db.cursor()

print("Search by: 1. Customer Name 2. Phone Number 3. Vehicle Number")

choice = int(input("Enter your choice: "))

if choice == 1:

name = input("Enter customer name: ")

cursor.execute("""

SELECT c.Name, c.Phone, p.SlotID, p.EntryTime, p.IsOccupied

FROM Customers c

LEFT JOIN ParkingSlots p ON c.VehicleNumber = p.VehicleNumber

WHERE c.Name LIKE %s

""", (f"%{name}%",))

elif choice == 2:

phone = input("Enter phone number: ")

cursor.execute("""

SELECT c.Name, c.Phone, p.SlotID, p.EntryTime, p.IsOccupied

FROM Customers c

LEFT JOIN ParkingSlots p ON c.VehicleNumber = p.VehicleNumber

WHERE c.Phone = %s

""", (phone,))

elif choice == 3:

vehicle_number = input("Enter vehicle number: ")

cursor.execute("""

SELECT c.Name, c.Phone, p.SlotID, p.EntryTime, p.IsOccupied

FROM Customers c

LEFT JOIN ParkingSlots p ON c.VehicleNumber = p.VehicleNumber

WHERE c.VehicleNumber = %s

""", (vehicle_number,))
else:

print("Invalid choice.")

return

rows = cursor.fetchall()

if rows:

print("Name | Phone | SlotID | EntryTime | Occupied")

for row in rows:

print(f"{row[0]} | {row[1]} | {row[2]} | {row[3]} | {row[4]}")

else:

print("No records found.")

db.close()

def add_parking_slots():

db = connect_to_db()

cursor = db.cursor()

num_slots = int(input("Enter the number of parking slots to add: "))

level = int(input("Enter the parking level: "))

for _ in range(num_slots):

cursor.execute("INSERT INTO ParkingSlots (IsOccupied, Level) VALUES (FALSE, %s)", (level,))

db.commit()

print(f"{num_slots} parking slots added on Level {level} successfully.")

db.close()

def view_parking_status():

db = connect_to_db()

cursor = db.cursor()

cursor.execute("SELECT * FROM ParkingSlots")


rows = cursor.fetchall()

print("SlotID | Level | VehicleNumber | VehicleType | EntryTime | ExitTime |


IsOccupied")

for row in rows:

print(f"{row[0]} | {row[6]} | {row[1] or 'None'} | {row[2] or 'None'} | {row[3] or


'None'} | {row[4] or 'None'} | {row[5]}")

db.close()

def reserve_slot():

db = connect_to_db()

cursor = db.cursor()

vehicle_number = input("Enter vehicle number for reservation: ")

reservation_time = input("Enter reservation time (YYYY-MM-DD HH:MM:SS): ")

cursor.execute("SELECT SlotID FROM ParkingSlots WHERE IsOccupied = FALSE AND ReservedFor IS


NULL LIMIT 1")

slot = cursor.fetchone()

if slot:

slot_id = slot[0]

cursor.execute("""

UPDATE ParkingSlots

SET Reserved = TRUE, VehicleNumber = %s, ReservedFor = %s

WHERE SlotID = %s

""", (vehicle_number, reservation_time, slot_id))

db.commit()

print(f"Slot {slot_id} reserved successfully for {reservation_time}.")

else:

print("No available slots for reservation.")


db.close()

def generate_monthly_report():

db = connect_to_db()

cursor = db.cursor()

month = input("Enter the month (YYYY-MM): ")

cursor.execute("""

SELECT DATE(ExitTime) AS Date, SUM(Fee) AS TotalRevenue, COUNT(*) AS TotalVehicles

FROM ParkingSlots

WHERE ExitTime LIKE %s

GROUP BY DATE(ExitTime)

""", (f"{month}%",))

rows = cursor.fetchall()

print("Date | Total Revenue | Total Vehicles")

for row in rows:

print(f"{row[0]} | ${row[1]:.2f} | {row[2]}")

db.close()

# Main Menu

def main():

print("--- Admin Login ---")

if not admin_login():

return

while True:

print("\n--- Parking Management System ---")

print("1. Add Parking Slots")

print("2. Check In Vehicle")


print("3. Check Out Vehicle")

print("4. View Parking Status")

print("5. View Daily Revenue")

print("6. Search Vehicle")

print("7. Reserve Parking Slot")

print("8. Parking Slot Utilization Report")

print("9. Display Real-Time Availability")

print("10. Register Customer")

print("11. View Customers")

print("12. Advanced Search")

print("13. Generate Monthly Report")

print("14. Exit")

try:

choice = int(input("Enter your choice: "))

if choice == 1:

add_parking_slots()

elif choice == 2:

check_in_vehicle()

elif choice == 3:

check_out_vehicle()

elif choice == 4:

view_parking_status()

elif choice == 5:

view_daily_revenue()

elif choice == 6:

search_vehicle()

elif choice == 7:

reserve_slot()

elif choice == 8:

slot_utilization_report()
elif choice == 9:

display_parking_availability()

elif choice == 10:

register_customer()

elif choice == 11:

view_customers()

elif choice == 12:

advanced_search()

elif choice == 13:

generate_monthly_report()

elif choice == 14:

print("Exiting the system. Goodbye!")

break

else:

print("Invalid choice. Please try again.")

except ValueError:

print("Invalid input. Please enter a number.")

# Run the system

if __name__ == "__main__":

main()

mysql

CREATE DATABASE ParkingDB;

USE ParkingDB;

CREATE TABLE ParkingSlots (

SlotID INT AUTO_INCREMENT PRIMARY KEY,


VehicleNumber VARCHAR(20),

VehicleType VARCHAR(20),

EntryTime DATETIME,

ExitTime DATETIME,

IsOccupied BOOLEAN DEFAULT FALSE

);

You might also like