File: query_strings_as_bytes.py

package info (click to toggle)
python-cx-oracle 8.3.0-3
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm, sid
  • size: 3,276 kB
  • sloc: ansic: 10,406; python: 9,358; sql: 1,724; makefile: 31
file content (49 lines) | stat: -rw-r--r-- 2,038 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#------------------------------------------------------------------------------
# Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# query_strings_as_bytes.py
#
# Demonstrates how to query strings as bytes (bypassing decoding of the bytes
# into a Python string). This can be useful when attempting to fetch data that
# was stored in the database in the wrong encoding.
#
# This script requires cx_Oracle 8.2 and higher.
#------------------------------------------------------------------------------

import cx_Oracle as oracledb
import sample_env

STRING_VAL = 'I bought a cafetière on the Champs-Élysées'

def return_strings_as_bytes(cursor, name, default_type, size, precision,
                            scale):
    if default_type == oracledb.DB_TYPE_VARCHAR:
        return cursor.var(str, arraysize=cursor.arraysize, bypass_decode=True)

with oracledb.connect(sample_env.get_main_connect_string()) as conn:

    # truncate table and populate with our data of choice
    with conn.cursor() as cursor:
        cursor.execute("truncate table TestTempTable")
        cursor.execute("insert into TestTempTable values (1, :val)",
                       val=STRING_VAL)
        conn.commit()

    # fetch the data normally and show that it is returned as a string
    with conn.cursor() as cursor:
        cursor.execute("select IntCol, StringCol from TestTempTable")
        print("Data fetched using normal technique:")
        for row in cursor:
            print(row)
        print()

    # fetch the data, bypassing the decode and show that it is returned as
    # bytes
    with conn.cursor() as cursor:
        cursor.outputtypehandler = return_strings_as_bytes
        cursor.execute("select IntCol, StringCol from TestTempTable")
        print("Data fetched using bypass decode technique:")
        for row in cursor:
            print(row)