python-cx_Oracle/samples/ReturnNumbersAsDecimals.py
Anthony Tuininga 340dcb7195 Rework test suite and samples so that they are independent of each other and
so that the SQL scripts used to create/drop schemas are easily adjusted to
use different schema names, if desired. Improve documentation for test suite
and samples.
2017-07-14 16:50:41 -06:00

35 lines
1.4 KiB
Python

#------------------------------------------------------------------------------
# Copyright 2017, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# ReturnNumbersAsDecimals.py
# Returns all numbers as decimals by means of an output type handler. This is
# needed if the full decimal precision of Oracle numbers is required by the
# application. See this article
# (http://blog.reverberate.org/2016/02/06/floating-point-demystified-part2.html)
# for an explanation of why decimal numbers (like Oracle numbers) cannot be
# represented exactly by floating point numbers.
#
# This script requires cx_Oracle 5.0 and higher.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import decimal
import SampleEnv
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.NUMBER:
return cursor.var(str, size = 200, arraysize = cursor.arraysize,
outconverter = decimal.Decimal)
connection = cx_Oracle.Connection(SampleEnv.MAIN_CONNECT_STRING)
connection.outputtypehandler = OutputTypeHandler
cursor = connection.cursor()
cursor.execute("select * from TestNumbers")
for row in cursor:
print("Row:", row)