1

I need to find out what kind of database I am working against based on data from an dbapi cursor instance. Have not found any clues on how to do this in the dbapi docs. Can it be done?

1 Answer 1

2

It isn't part of the dbapi 2.0, at least to my knowledge. However, you can implement a function to obtain the module name from a given database object (cursor, connection) and map that to a well-known string for your application to use:

_DBNAME_MAP = {
    'psycopg2': 'postgres',
    'MySQLdb': 'mysql',
    'sqlite3': 'sqlite',
    'sqlite': 'sqlite'
    }

def get_dbname(dbobj):
    mod = dbobj.__class__.__module__.split('.', 1)[0]
    return _DBNAME_MAP.get(mod)

Examples:

>>> s_conn = sqlite3.connect('foo.db')
>>> get_dbname(s_conn)
'sqlite'
>>> get_dbname(s_conn.cursor())
'sqlite'

>>> p_conn = psycopg2.connect('host=localhost user=postgres')
>>> get_dbname(p_conn)
'postgres'
>>> get_dbname(p_conn.cursor())
'postgres'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.