fork download
  1. #!/usr/bin/python
  2.  
  3.  
  4. import os,sys
  5. from datetime import datetime,timedelta
  6. import cx_Oracle as orcl
  7. import mysql.connector as pymysql
  8. from pprint import pprint
  9.  
  10. alarms = {198087342:'2G'}
  11.  
  12. db=orcl.connect('sys','oracle','minos',mode=orcl.SYSDBA)
  13. cursor =db.cursor()
  14. cursor.execute("select position1,customattr5,to_char(alarmraisedtime_gmt,'YYYY-MM-DD HH24:MI:SS'),code from CAFFM4X.currentalarm where code in ('198087342')")
  15. p=cursor.fetchall()
  16.  
  17. print p
  18.  
  19.  
  20. conn = pymysql.connect(user='omcr',password='omcr',host='117.239.216.50',database='omcr')
  21. mycursor = conn.cursor()
  22.  
  23. for j in p:
  24. values =[j[1][0:17],j[1][0:15],j[0].split('@')[-2],'Zte',alarms[j[3]],datetime.strptime(j[2],'%Y-%m-%d %H:%M:%S')]
  25. #bts_name=j[1].split('_')[-2]
  26. print values
  27. sql=("insert ignore into omcr.currentbtsdown_sectors(sector_name,bts_name,bsc_name,make,tech,down_time) values(%s,%s,%s,%s,%s,%s)")
  28. mycursor.execute(sql,(values))
  29.  
  30.  
  31. cursor.execute("select position1,customattr5,to_char(alarmraisedtime_gmt,'YYYY-MM-DD HH24:MI:SS'),to_char(alarmclearedtime,'YYYY-MM-DD HH24:MI:SS'),code from CAFFM4X.historyalarm \
  32. where code in ('198087342') and alarmclearedtime>sysdate-3/24")
  33.  
  34. outage = cursor.fetchall()
  35.  
  36. for k in outage:
  37. values =[k[1][0:17],k[1][0:15],k[0].split('@')[-2],'Zte',alarms[k[4]],datetime.strptime(k[2],'%Y-%m-%d %H:%M:%S'),datetime.strptime(k[3],'%Y-%m-%d %H:%M:%S')]
  38. #print values
  39. sql = ("replace into omcr.currentbtsdown_sectors(sector_name,bts_name,bsc_name,make,tech,down_time,up_time) values(%s,%s,%s,%s,%s,%s,%s)")
  40. mycursor.execute(sql,(values))
  41.  
  42.  
  43. conn.commit()
  44. conn.close()
  45. # your code goes here
Success #stdin #stdout 0.02s 25976KB
stdin
import mysql.connector
import pandas as pd
import os
from random import randint

class TrainTicketSystem:
    def __init__(self):
        self.db = mysql.connector.connect(
            host="localhost",
            user="root",
            password="1234"
        )
        self.cursor = self.db.cursor()
        self.initialize_database()

    def initialize_database(self):
        try:
            # Create the database if it doesn't exist
            self.cursor.execute("CREATE DATABASE IF NOT EXISTS train_ticket_system")
            self.cursor.execute("USE train_ticket_system")

            # Create tables
            queries = [
                "CREATE TABLE IF NOT EXISTS admins (name VARCHAR(100), mo_no VARCHAR(15), address VARCHAR(255), email VARCHAR(100), username VARCHAR(50) PRIMARY KEY, password VARCHAR(50))",
                "CREATE TABLE IF NOT EXISTS customers (name VARCHAR(100), mo_no VARCHAR(15), address VARCHAR(255), email VARCHAR(100), username VARCHAR(50) PRIMARY KEY, password VARCHAR(50))",
                "CREATE TABLE IF NOT EXISTS tickets (pnr BIGINT PRIMARY KEY, class VARCHAR(50), boarding_point VARCHAR(100), quota VARCHAR(50))",
                "CREATE TABLE IF NOT EXISTS train_schedule (id INT AUTO_INCREMENT PRIMARY KEY, train_name VARCHAR(100), source VARCHAR(100), destination VARCHAR(100), time VARCHAR(50))"
            ]
            for query in queries:
                self.cursor.execute(query)
            self.db.commit()
        except mysql.connector.Error as err:
            print("Error initializing database:", err)

    def admin_signup(self, name, mo_no, address, email, username, password):
        try:
            self.cursor.execute(
                "INSERT INTO admins (name, mo_no, address, email, username, password) VALUES (%s, %s, %s, %s, %s, %s)",
                (name, mo_no, address, email, username, password)
            )
            self.db.commit()
            print("Admin account created.")
        except mysql.connector.Error as err:
            print("Error:", err)

    def customer_signup(self, name, mo_no, address, email, username, password):
        try:
            self.cursor.execute(
                "INSERT INTO customers (name, mo_no, address, email, username, password) VALUES (%s, %s, %s, %s, %s, %s)",
                (name, mo_no, address, email, username, password)
            )
            self.db.commit()
            print("Customer account created.")
        except mysql.connector.Error as err:
            print("Error:", err)

    def book_ticket(self):
        ticket_class = input("Enter ticket class (e.g., Sleeper, AC): ")
        boarding_point = input("Enter boarding point: ")
        quota = input("Enter quota (e.g., General, Tatkal): ")
        try:
            pnr = randint(1000000000, 9999999999)
            self.cursor.execute(
                "INSERT INTO tickets (pnr, class, boarding_point, quota) VALUES (%s, %s, %s, %s)",
                (pnr, ticket_class, boarding_point, quota)
            )
            self.db.commit()
            print(f"Ticket booked successfully with PNR: {pnr}")
        except mysql.connector.Error as err:
            print("Error:", err)

    def view_tickets(self):
        self.cursor.execute("SELECT * FROM tickets")
        tickets = self.cursor.fetchall()
        if tickets:
            for ticket in tickets:
                print(f"PNR: {ticket[0]}, Class: {ticket[1]}, Boarding Point: {ticket[2]}, Quota: {ticket[3]}")
        else:
            print("No tickets available.")

    def add_train_schedule(self):
        train_name = input("Enter train name: ")
        source = input("Enter source station: ")
        destination = input("Enter destination station: ")
        time = input("Enter departure time (HH:MM): ")
        try:
            self.cursor.execute(
                "INSERT INTO train_schedule (train_name, source, destination, time) VALUES (%s, %s, %s, %s)",
                (train_name, source, destination, time)
            )
            self.db.commit()
            print("Train schedule added successfully.")
        except mysql.connector.Error as err:
            print("Error:", err)

    def view_train_schedule(self):
        self.cursor.execute("SELECT * FROM train_schedule")
        schedules = self.cursor.fetchall()
        if schedules:
            for schedule in schedules:
                print(f"Train: {schedule[1]}, Source: {schedule[2]}, Destination: { schedule[3]}, Time: {schedule[4]}")
        else:
            print("No train schedules available.")

    def export_to_excel(self, table_name):
        try:
            self.cursor.execute(f"SELECT * FROM {table_name}")
            rows = self.cursor.fetchall()
            columns = [desc[0] for desc in self.cursor.description]

            df = pd.DataFrame(rows, columns=columns)
            desktop = os.path.join(os.path.expanduser("~"), "Desktop")
            file_path = os.path.join(desktop, f"{table_name}.xlsx")

            df.to_excel(file_path, index=False)
            print(f"Data exported to {file_path}")
        except mysql.connector.Error as err:
            print("Error:", err)
        except Exception as ex:
            print("Unexpected error:", ex)

# Main Menu
def main():
    system = TrainTicketSystem()
    while True:
        print('\n╔═[Main Menu]══════════════════╗')
        print(' 1. Admin SignUp')
        print(' 2. Customer SignUp')
        print(' 3. Book Ticket')
        print(' 4. View Tickets')
        print(' 5. Add Train Schedule')
        print(' 6. View Train Schedules')
        print(' 7. Export Data to Excel')
        print(' 8. Exit')
        print('╚══════════════════════════════╝')

        try:
            choice = int(input("Enter Your Choice: "))
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue

        if choice == 1:
            system.admin_signup("Admin1", "1234567890", "Address1", "admin@example.com", "admin", "password")
        elif choice == 2:
            system.customer_signup("Customer1", "0987654321", "Address2", "cust@example.com", "customer", "password")
        elif choice == 3:
            system.book_ticket()
        elif choice == 4:
            system.view_tickets()
        elif choice == 5:
            system.add_train_schedule()
        elif choice == 6:
            system.view_train_schedule()
        elif choice == 7:
            table_name = input("Enter table name to export (admins/customers/tickets/train_schedule): ")
            system.export_to_excel(table_name)
        elif choice == 8:
            print("Exiting... Goodbye!")
            break
        else:
            print("Invalid choice. Please try again.")

main()
stdout

import os,sys
from datetime import datetime,timedelta
import cx_Oracle as orcl
import mysql.connector as pymysql
from pprint import pprint

alarms = {198087342:'2G'}

db=orcl.connect('sys','oracle','minos',mode=orcl.SYSDBA)
cursor =db.cursor()
cursor.execute("select position1,customattr5,to_char(alarmraisedtime_gmt,'YYYY-MM-DD HH24:MI:SS'),code from CAFFM4X.currentalarm  where code in ('198087342')")
p=cursor.fetchall()

print p


conn = pymysql.connect(user='omcr',password='omcr',host='117.239.216.50',database='omcr')
mycursor = conn.cursor()

for j in p:
	values =[j[1][0:17],j[1][0:15],j[0].split('@')[-2],'Zte',alarms[j[3]],datetime.strptime(j[2],'%Y-%m-%d %H:%M:%S')]
	#bts_name=j[1].split('_')[-2]
	print values
	sql=("insert ignore into omcr.currentbtsdown_sectors(sector_name,bts_name,bsc_name,make,tech,down_time) values(%s,%s,%s,%s,%s,%s)")
        mycursor.execute(sql,(values))

	
cursor.execute("select position1,customattr5,to_char(alarmraisedtime_gmt,'YYYY-MM-DD HH24:MI:SS'),to_char(alarmclearedtime,'YYYY-MM-DD HH24:MI:SS'),code from CAFFM4X.historyalarm  \
where code in ('198087342') and alarmclearedtime>sysdate-3/24")

outage = cursor.fetchall()

for k in outage:
	values =[k[1][0:17],k[1][0:15],k[0].split('@')[-2],'Zte',alarms[k[4]],datetime.strptime(k[2],'%Y-%m-%d %H:%M:%S'),datetime.strptime(k[3],'%Y-%m-%d %H:%M:%S')]
	#print values
	sql = ("replace into omcr.currentbtsdown_sectors(sector_name,bts_name,bsc_name,make,tech,down_time,up_time) values(%s,%s,%s,%s,%s,%s,%s)")
	mycursor.execute(sql,(values))


conn.commit()
conn.close()
# your code goes here