nJoshi
nJoshi

Reputation: 376

Return Empty String in place of Oracle NULL/Python None when pulling data from Oracle using cx_Oracle

When I pull data using the cx_Oracle module, None is returned in place of Oracle NULL. At this point I'm using the below function to convert None to empty string.

def xstr(s):
    if s is None:
        return ''
    return str(s)

Is there a way to make the cx_Oracle module to return an empty string instead of None?

Upvotes: 1

Views: 2294

Answers (1)

Anthony Tuininga
Anthony Tuininga

Reputation: 7096

You can use an output type handler and out converter to transform this way. Something like this.

def OutConverter(value):
    if value is None:
        return ''
    return value

def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
    if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
        return cursor.var(str, size, cursor.arraysize, outconverter=OutConverter)

connection.outputtypehandler = OutputTypeHandler

The above code will transform any null strings that are returned from the database to empty strings.

Upvotes: 3

Related Questions