Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Exception Hanlding of Lists
#1
Hello,

I'm writing a program that will list available databases to a user based on their tnsnames.ora and then allow them to make a connection to one available. I want to return a message if they attempt to use something other than what's available in the list.

Here is a snippet of the code:
def db_menu():
    os.chdir(r'c:\temp')  # move to tns directoy; raw string

    tns = open('tnsnames.ora', 'r')  # open file in read mode
    sList = tns.read()  # read file into string
    sList = re.sub("#.*\n", "", sList)  # strip all comments
    sList = re.sub("\(.*\n", "", sList)  # remove "(" to end of line
    sList = re.sub("\)", "", sList)  # clean up ")"
    sList = re.sub(" ", "", sList)  # remove spaces
    sList = re.sub("\n", "", sList)  # remove carriage returns
    sList = re.sub("=$", "", sList)  # remove last "="
    sList = sList.split("=")  # create list
    tns.close()

    print('\nAvailable Databases: ')
    for i in sList:
        print(i)

# Database Login
def db_login():
    db_menu()
    while True:
        try:
            # Input username and password

            uname = input('\nEnter username: ')
            pw = getpass.getpass(prompt='Enter password: ')
            db = input('Enter database: ')
            conn_str = u'%s/%s@%s' % (uname, pw, db)                            # connection string
            conn = cx_Oracle.connect(conn_str)                                  # connection to database
            cur = conn.cursor()                                                 # parameter to access cursor method
            q_str = "select * from global_name"                                 # create a query string
            cur.execute(q_str)                                                  # pass to cursor method

            for row in cur:
                print("\nConnected to: {}".format(row))
            else:
                break

        except cx_Oracle.DatabaseError as e:
            error, = e.args
            print("\nInvalid username/password.  Please try again.\n")
Do I need to add another exception or would it be something of an if/else statement so they can continue to login once the correct database is entered?

Thanks!
Reply
#2
I'd move the file handling to it's own function, so it would be fine to call db_menu() multiple times. Then I'd write a while loop that just kept asking for a valid database to connect to. Something like:
def get_available_databases():
    os.chdir('c:/temp')  # move to tns directoy; raw string
    # open file in read mode
    with open('tnsnames.ora', 'r') as tns:
        sList = tns.read()  # read file into string
        sList = re.sub("#.*\n", "", sList)  # strip all comments
        sList = re.sub("\(.*\n", "", sList)  # remove "(" to end of line
        sList = re.sub("\)", "", sList)  # clean up ")"
        sList = re.sub(" ", "", sList)  # remove spaces
        sList = re.sub("\n", "", sList)  # remove carriage returns
        sList = re.sub("=$", "", sList)  # remove last "="
        sList = sList.split("=")  # create list
        return sList

def db_menu(db_names):
    print('\nAvailable Databases: ')
    for i in db_names:
        print(i)
 
def select_db_name(available_db_names):
    while True:
        db_menu(available_db_names)
        selection = input('Enter database: ')
        if selection in available_db_names:
            return selection
        print("Database unavailable.")

# Database Login
def db_login():
    available_db_names = get_available_databases()
    while True:
        try:
            # Input username and password
 
            uname = input('\nEnter username: ')
            pw = getpass.getpass(prompt='Enter password: ')
            db = select_db_name(available_db_names)
            conn_str = u'%s/%s@%s' % (uname, pw, db)                            # connection string
            conn = cx_Oracle.connect(conn_str)                                  # connection to database
            cur = conn.cursor()                                                 # parameter to access cursor method
            q_str = "select * from global_name"                                 # create a query string
            cur.execute(q_str)                                                  # pass to cursor method
 
            for row in cur:
                print("\nConnected to: {}".format(row))
            else:
                break
 
        except cx_Oracle.DatabaseError as e:
            error, = e.args
            print("\nInvalid username/password.  Please try again.\n")
Reply
#3
This worked! Great advice and awesome code! Much appreciated!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,361 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,254 Mar-20-2019, 08:01 PM
Last Post: stillsen
  During handling of the above exception, another exception occurred Skaperen 7 26,866 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020