Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 419119
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T18:44:45+00:00 2026-05-12T18:44:45+00:00

I want my code to automatically try multiple ways to create a database connection.

  • 0

I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn’t try to other ways anymore). If they all fail well, then the script can just blow up.

So in – what I thought was, but most likely isn’t – a stroke of genius I tried this:

import psycopg2
from getpass import getpass

# ouch, global variable, ooh well, it's just a simple script eh
CURSOR = None

def get_cursor():
    """Create database connection and return standard cursor."""

    global CURSOR

    if not CURSOR:
        # try to connect and get a cursor
        try:
            # first try the bog standard way: db postgres, user postgres and local socket
            conn = psycopg2.connect(database='postgres', user='postgres')
        except psycopg2.OperationalError:
            # maybe user pgsql?
            conn = psycopg2.connect(database='postgres', user='pgsql')
        except psycopg2.OperationalError:
            # maybe it was postgres, but on localhost? prolly need password then
            conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass())
        except psycopg2.OperationalError:
            # or maybe it was pgsql and on localhost
            conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass())

        # allright, nothing blew up, so we have a connection
        # now make a cursor
        CURSOR = conn.cursor()

    # return existing or new cursor
    return CURSOR

But it seems that the second and subsequent except statements aren’t catching the OperationalErrors anymore. Probably because Python only catches an exception once in a try…except statement?

Is that so? If not: is there anything else I’m doing wrong? If so: how do you do something like this then? Is there a standard idiom?

(I know there are ways around this problem, like having the user specify the connection parameters on the command line, but that’s not my question ok 🙂 )

EDIT:

I accepted retracile’s excellent answer and I took in gnibbler’s comment for using the for..else construct. The final code became (sorry, I’m not really following the max characters per line limit from pep8):

EDIT 2: As you can see from the comment on the Cursor class: I don’t really know how to call this kind of class. It’s not really a singleton (I can have multiple different instances of Cursor) but when calling get_cursor I do get the same cursor object everytime. So it’s like a singleton factory? 🙂

import psycopg2
from getpass import getpass
import sys

class UnableToConnectError(Exception):
    pass

class Cursor:
    """Cursor singleton factory?"""

    def __init__(self):
        self.CURSOR = None

    def __call__(self):
        if self.CURSOR is None:
            # try to connect and get a cursor
            attempts = [
                    {'database': 'postgres', 'user': 'postgres'},
                    {'database': 'postgres', 'user': 'pgsql'},
                    {'database': 'postgres', 'user': 'postgres', 'host': 'localhost', 'password': None},
                    {'database': 'postgres', 'user': 'pgsql', 'host': 'localhost', 'password': None},
                    ]

            for attempt in attempts:
                if 'password' in attempt:
                    attempt['password'] = getpass(stream=sys.stderr) # tty and stderr are default in 2.6, but 2.5 uses sys.stdout, which I don't want
                try:
                    conn = psycopg2.connect(**attempt)

                    attempt.pop('password', None)
                    sys.stderr.write("Succesfully connected using: %s\n\n" % attempt)

                    break # no exception raised, we have a connection, break out of for loop
                except psycopg2.OperationalError:
                    pass
            else:
                raise UnableToConnectError("Unable to connect: exhausted standard permutations of connection dsn.")

            # allright, nothing blew up, so we have a connection
            # now make a cursor
            self.CURSOR = conn.cursor()

        # return existing or new cursor
        return self.CURSOR
get_cursor = Cursor()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T18:44:46+00:00Added an answer on May 12, 2026 at 6:44 pm

    Approximately:

    attempts = [
        { 'database'='postgres', 'user'='pgsql', ...},
        { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()},
        ...
    ]
    conn = None
    for attempt in attempts:
        try:
            conn = psycopg2.connect(**attempt)
            break
        except psycopg2.OperationalError:
            pass
    if conn is None:
        raise a ruckus
    CURSOR = conn.cursor()
    

    Now, if you don’t want to call getpass() unless it is necessary, you’d want to check if 'password' in attempt: attempt['password'] = getpass() or so.

    Now about that global….

    class MyCursor:
        def __init__(self):
            self.CURSOR = None
        def __call__(self):
            if self.CURSOR is None:
                <insert logic here>
            return self.CURSOR
    
    get_cursor = MyCursor()
    

    … though I think there are a couple of other ways to accomplish the same thing.

    Bringing it all together:

    class MyCursor:
        def __init__(self):
            self.CURSOR = None
        def __call__(self):
            if self.CURSOR is None:
                attempts = [
                    {'database'='postgres', 'user'='postgres'},
                    {'database'='postgres', 'user'='pgsql'},
                    {'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=True},
                    {'database'='postgres', 'user'='pgsql', 'host'='localhost', 'password'=True},
                ]
                conn = None
                for attempt in attempts:
                    if 'password' in attempt:
                        attempt['password'] = getpass()
                    try:
                        conn = psycopg2.connect(**attempt)
                        break # that didn't throw an exception, we're done
                    except psycopg2.OperationalError:
                        pass
                if conn is None:
                    raise a ruckus # nothin' worked
                self.CURSOR = conn.cursor()
            return self.CURSOR
    get_cursor = MyCursor()
    

    Note: completely untested

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 204k
  • Answers 204k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer (I'm assuming it knows that the id is the primary… May 12, 2026 at 8:50 pm
  • Editorial Team
    Editorial Team added an answer Here's how I'd improve the comparator: First, exctract a method… May 12, 2026 at 8:50 pm
  • Editorial Team
    Editorial Team added an answer Assuming "date" is the date string and "time" is the… May 12, 2026 at 8:50 pm

Related Questions

I've been using Git now for a couple of months on a project with
How do I suppress an exception in C#? I do not want to enclose
I am converting an application from BDE to ADO. Under the BDE, if a
I'm writing my first rails plugin and could use a little help. In a
I have an Asp .net page like this simple one http://issamsoft.com/app2/page1.aspx and I want

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.