Search code examples
pythondatabasepython-db-api

Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python


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?


Solution

  • 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'