Codebase list python-cx-oracle / 079927c
Various documentation and tutorial improvements. Anthony Tuininga 3 years ago
12 changed file(s) with 272 addition(s) and 147 deletion(s). Raw diff Collapse all Expand all
207207 edition=None, timeout=0, waitTimeout=0, maxLifetimeSession=0, \
208208 sessionCallback=None, maxSessionsPerShard=0)
209209
210 Create and return a :ref:`session pool object <sesspool>`.
210 Create and return a :ref:`session pool object <sesspool>`. Session pooling
211 (also known as connection pooling) creates a pool of available connections
212 to the database, allowing applications to acquire a connection very quickly.
213 It is of primary use in a server where connections are requested in rapid
214 succession and used for a short period of time, for example in a web server.
215 See :ref:`connpool` for more information.
216
211217 Connection pooling in cx_Oracle is handled by Oracle's
212218 `Session pooling <https://www.oracle.com/pls/topic/lookup?
213219 ctx=dblatest&id=GUID-F9662FFB-EAEF-495C-96FC-49C6D1D9625C>`__
215221 like `Application Continuity <https://www.oracle.com/pls/topic/lookup?
216222 ctx=dblatest&id=GUID-A8DD9422-2F82-42A9-9555-134296416E8F>`__.
217223
218 See :ref:`connpool` for information on connection pooling.
219
220 Session pooling creates a pool of available connections to the
221 database, allowing applications to acquire a connection very quickly.
222 It is of primary use in a server where connections are requested
223 in rapid succession and used for a short period of time, for example in a
224 web server.
225
226 If the connection type is specified, all calls to
224 The user, password and dsn parameters are the same as for
225 :meth:`cx_Oracle.connect()`
226
227 The min, max and increment parameters control pool growth behavior. A fixed
228 pool size where min equals max is recommended to help prevent connection
229 storms and to help overall system stability. The min parameter is the
230 number of connections opened when the pool is created. The increment is the
231 number of connections that are opened whenever a connection request exceeds
232 the number of currently open connections. The max parameter is the maximum
233 number of connections that can be open in the connection pool. Note that
234 when :ref:`external authentication <extauth>` or :ref:`heterogeneous pools
235 <connpooltypes>` are used, the pool growth behavior is different.
236
237 If the connectiontype parameter is specified, all calls to
227238 :meth:`~SessionPool.acquire()` will create connection objects of that type,
228239 rather than the base type defined at the module level.
229240
232243 Doing so in single threaded applications imposes a performance penalty of
233244 about 10-15% which is why the default is False.
234245
246 The getmode parameter indicates whether or not future
247 :func:`SessionPool.acquire()` calls will wait for available connections. It
248 can be one of the :ref:`Session Pool Get Modes <sesspoolmodes>` values.
249
235250 The events parameter is expected to be a boolean expression which indicates
236251 whether or not to initialize Oracle in events mode. This is required for
237252 continuous query notification and high availability event notifications.
240255 indicates whether or not to create a homogeneous pool. A homogeneous pool
241256 requires that all connections in the pool use the same credentials. As such
242257 proxy authentication and external authentication is not possible with a
243 homogeneous pool.
258 homogeneous pool. See :ref:`Heterogeneous and Homogeneous Connection Pools
259 <connpooltypes>`.
244260
245261 The externalauth parameter is expected to be a boolean expression which
246262 indicates whether or not external authentication should be used. External
247263 authentication implies that something other than the database is
248264 authenticating the user to the database. This includes the use of operating
249 system authentication and Oracle wallets.
250
251 See the :ref:`globalization <globalization>` section for details on the
252 encoding and nencoding parameters. Note the default encoding and nencoding
253 values changed to "UTF-8" in cx_Oracle 8, and any character set in NLS_LANG
254 is ignored.
255
256 The edition parameter is expected to be a string, if specified, and sets
257 the edition to use for the sessions in the pool. It is only relevant if
258 both the client and the server are at least Oracle Database 11.2.
265 system authentication and Oracle wallets. See :ref:`Connecting Using
266 External Authentication <extauth>`.
267
268 The encoding and nencoding parameters set the encodings used for string
269 values transferred between cx_Oracle and Oracle Database, see
270 :ref:`Character Sets and Globalization <globalization>`. Note the default
271 encoding and nencoding values changed to "UTF-8" in cx_Oracle 8, and any
272 character set in NLS_LANG is ignored.
273
274 The edition parameter is expected to be a string, if specified, and sets the
275 edition to use for the sessions in the pool. It is only relevant if both the
276 client and the server are at least Oracle Database 11.2. See
277 :ref:`Edition-Based Redefinition (EBR) <ebr>`.
259278
260279 The timeout parameter is expected to be an integer, if specified, and sets
261280 the length of time (in seconds) after which idle sessions in the pool are
278297 may exist.
279298
280299 The sessionCallback parameter is expected to be either a string or a
281 callable. If the parameter is a string, this refers to a PL/SQL procedure
282 that will be called when :func:`SessionPool.acquire()` requests a tag and
283 that tag does not match the connection's actual tag. Support for the PL/SQL
284 procedure requires Oracle Client libraries 12.2 or later. See the
285 `OCI documentation <https://www.oracle.com/pls/topic/lookup?
286 ctx=dblatest&id=GUID-B853A020-752F-494A-8D88-D0396EF57177>`__ for more
287 information. If the sessionCallback parameter is a callable, however, it
288 will be called when a newly created connection is returned from the pool
289 or when a tag is requested and that tag does not match the connection's
290 actual tag. The callable will be invoked with the connection and the
291 requested tag as its only parameters.
300 callable. If the sessionCallback parameter is a callable, it will be called
301 when a newly created connection is returned from the pool, or when a tag is
302 requested and that tag does not match the connection's actual tag. The
303 callable will be invoked with the connection and the requested tag as its
304 only parameters. If the parameter is a string, it should be the name of a
305 PL/SQL procedure that will be called when :func:`SessionPool.acquire()`
306 requests a tag and that tag does not match the connection's actual tag. See
307 :ref:`Session CallBacks for Setting Pooled Connection State
308 <sessioncallback>`. Support for the PL/SQL procedure requires Oracle Client
309 libraries 12.2 or later. See the `OCI documentation
310 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&
311 id=GUID-B853A020-752F-494A-8D88-D0396EF57177>`__ for more information.
292312
293313 The maxSessionsPerShard parameter is expected to be an integer, if
294314 specified, and sets the maximum number of sessions in the pool that can be
822842 This constant is used to specify that messages should be sent when data is
823843 updated, or that the message identifies a row that has been updated.
824844
845 .. _sesspoolmodes:
825846
826847 Session Pool Get Modes
827848 ----------------------
149149
150150 This read-write attribute specifies the size of the statement cache that
151151 will be used as the starting point for any connections that are created by
152 the session pool. Once created, the connection's statement cache size can
153 only be changed by setting the stmtcachesize attribute on the connection
154 itself.
152 the session pool. Once a connection is created, that connection's statement
153 cache size can only be changed by setting the
154 :attr:`Connection.stmtcachesize` attribute on the connection itself.
155
156 See :ref:`Statement Caching <stmtcache>` for more information.
155157
156158 .. versionadded:: 6.0
157159
99
1010 .. centered:: **LICENSE AGREEMENT FOR CX_ORACLE**
1111
12 Copyright |copy| 2016, 2018, Oracle and/or its affiliates. All rights reserved.
12 Copyright |copy| 2016, 2020, Oracle and/or its affiliates. All rights reserved.
1313
1414 Copyright |copy| 2007-2015, Anthony Tuininga. All rights reserved.
1515
323323 can explicitly initiate a full ping to check connection liveness with
324324 :meth:`Connection.ping()` but overuse will impact performance and scalability.
325325
326 The Oracle Real-World Performance Group's general recommendation for connection
327 pools is use a fixed sized pool. The values of `min` and `max` should be the
328 same (and `increment` equal to zero). the firewall, `resource manager
326 The Oracle Real-World Performance Group's recommendation is to use fixed size
327 connection pools. The values of min and max should be the same (and the
328 increment equal to zero). The :ref:`firewall <hanetwork>`, `resource manager
329329 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-2BEF5482-CF97-4A85-BD90-9195E41E74EF>`__
330330 or user profile `IDLE_TIME
331331 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-ABC7AE4D-64A8-4EA9-857D-BEF7300B64C3>`__
334334 Static Pools
335335 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-7DFBA826-7CC0-4D16-B19C-31D168069B54>`__,
336336 which contains details about sizing of pools.
337
338 The Real-World Performance Group also recommends keeping pool sizes small, as
339 they may perform better than larger pools. The pool attributes should be
340 adjusted to handle the desired workload within the bounds of available resources
341 in cx_Oracle and the database.
337342
338343 .. _sessioncallback:
339344
3737 database installation, such as Oracle Database "XE" Express Edition, then
3838 you will need to have previously set your environment to use that
3939 software installation, otherwise files such as message files will not be
40 located. If the Oracle Client libraries cannot be loaded from
41 ``lib_dir``, then an exception is raised.
40 located. On Windows when the path contains backslashes, use a 'raw'
41 string like ``lib_dir = r"C:\instantclient_19_6"``. If the Oracle Client
42 libraries cannot be loaded from ``lib_dir``, then an exception is raised.
4243
4344 - If ``lib_dir`` was not specified, then Oracle Client libraries are looked
4445 for in the directory where the cx_Oracle binary module is installed.
99 To use cx_Oracle 8 with Python and Oracle Database you need:
1010
1111 - Python 3.5 and higher. Older versions of cx_Oracle may work with older
12 versions of Python.
12 versions of Python, for example see :ref:`Installing cx_Oracle in Python 2
13 <python2>`
1314
1415 - Oracle Client libraries. These can be from the free `Oracle Instant
1516 Client
1718 or those included in Oracle Database if Python is on the same
1819 machine as the database. Oracle client libraries versions 19, 18, 12,
1920 and 11.2 are supported on Linux, Windows and macOS. Users have
20 also reported success with other platforms.
21
22 - An Oracle Database. Oracle's standard client-server version
23 interoperability allows cx_Oracle to connect to both older and newer
24 databases.
21 also reported success with other platforms. Use the latest client possible:
22 Oracle's standard client-server version interoperability allows connection to
23 both older and newer databases.
24
25 - An Oracle Database, either local or remote.
2526
2627 The cx_Oracle module loads Oracle Client libraries which communicate
2728 over Oracle Net to an existing database. Oracle Net is not a separate
3839 - Install `Python <https://www.python.org/downloads>`__ 3, if not already
3940 available. On macOS you must always install your own Python.
4041
41 Python 3.5 and higher are supported by cx_Oracle 8. For Python 2, use
42 cx_Oracle 7.3.
42 Python 3.5 and higher are supported by cx_Oracle 8. For Python 2, see
43 :ref:`Installing cx_Oracle in Python 2 <python2>`.
4344
4445 - Install cx_Oracle from `PyPI
4546 <https://pypi.org/project/cx-Oracle/>`__ with:
498499 import cx_Oracle
499500 cx_Oracle.init_oracle_client(lib_dir=r"C:\oracle\instantclient_19_6")
500501
502 Note a 'raw' string is used because backslashes occur in the path.
503
501504 * Alternatively, add the Oracle Instant Client directory to the ``PATH``
502505 environment variable. The directory must occur in ``PATH`` before any
503506 other Oracle directories. Restart any open command prompt windows.
785788 hosted. Use the supplied cx_Oracle Wheels instead, or use RPMs
786789 from Oracle, see :ref:`oraclelinux`.
787790
791 .. _python2:
792
793 Installing cx_Oracle in Python 2
794 ================================
795
796 To install cx_Oracle in Python 2, use a command like::
797
798 python -m pip install cx_Oracle==7.3 --upgrade --user
799
800 cx_Oracle 7.3 was the last version with support for Python 2.
801
802 For other installation options such as installing through a proxy, see
803 instructions above. Make sure the Oracle Client libraries are in the system
804 library search path because cx_Oracle 7 does not support the
805 :meth:`cx_Oracle.init_oracle_client()` method and does not support loading the
806 Oracle Client libraries from the directory containing the cx_Oracle module
807 binary.
788808
789809 Installing cx_Oracle 5.3
790810 ========================
233233 (1000, 1, 'BOOKS')
234234 (2000, 2, 'FURNITURE')
235235
236 .. _ebr:
236237
237238 Edition-Based Redefinition (EBR)
238239 --------------------------------
3636 Make good use of PL/SQL to avoid executing many individual statements from
3737 cx_Oracle.
3838
39 Tune the Statement Cache with :attr:`Connection.stmtcachesize`.
39 Tune the :ref:`Statement Cache <stmtcache>`.
4040
4141 Enable :ref:`Client Result Caching <clientresultcache>` for small lookup tables.
4242
257257 cx_Oracle's :meth:`Cursor.execute()` and :meth:`Cursor.executemany()` functions
258258 use the `Oracle Call Interface statement cache
259259 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-4947CAE8-1F00-4897-BB2B-7F921E495175>`__
260 to make re-execution of statements efficient. This cache removes most needs for
261 using the :meth:`Cursor.prepare()` method.
262
263 The statement cache size can be set with :attr:`Connection.stmtcachesize`.
264
265 Each non-pooled connection and each session in the connection pool has
266 its own cache of statements with a default size of 20. Statement
267 caching lets cursors be used without re-parsing the statement.
268 Statement caching also reduces meta data transfer costs between the
269 cx_Oracle and the database. Performance and scalability are
270 improved.
271
272 In general, set the statement cache to the size of the working set of
273 statements being executed by the application.
260 to make re-execution of statements efficient. Each standalone or pooled
261 connection has its own cache of statements with a default size of 20. Statement
262 caching lets cursors be used without re-parsing the statement. Statement
263 caching also reduces metadata transfer costs between the cx_Oracle and the
264 database. Performance and scalability are improved.
265
266 The statement cache size can be set with :attr:`Connection.stmtcachesize` or
267 :attr:`SessionPool.stmtcachesize`. In general, set the statement cache size to
268 the size of the working set of statements being executed by the application. To
269 manually tune the cache, monitor the general application load and the `Automatic
270 Workload Repository
271 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-56AEF38E-9400-427B-A818-EDEC145F7ACD>`__
272 (AWR) "bytes sent via SQL*Net to client" values. The latter statistic should
273 benefit from not shipping statement metadata to cx_Oracle. Adjust the statement
274 cache size to your satisfaction.
274275
275276 Statement caching can be disabled by setting the size to 0. Disabling
276277 the cache may be beneficial when the quantity or order of statements
282283 With Oracle Database 12c, or later, the statement cache size can be
283284 automatically tuned using the :ref:`oraaccess.xml <optclientfiles>` file.
284285
285 To manually tune the statement cache size, monitor general application load and
286 the `Automatic Workload Repository
287 <https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-56AEF38E-9400-427B-A818-EDEC145F7ACD>`__
288 (AWR) "bytes sent via SQL*Net to client" values. The latter statistic should
289 benefit from not shipping statement metadata to cx_Oracle. Adjust the statement
290 cache size to your satisfaction.
286 When it is inconvenient to pass statement text through an application, the
287 :meth:`Cursor.prepare()` call can be used to avoid statement re-parsing.
288 Subsequent ``execute()`` calls use the value ``None`` instead of the SQL text:
289
290 .. code-block:: python
291
292 cur.prepare("select * from dept where deptno = :id order by deptno")
293
294 cur.execute(None, id = 20)
295 res = cur.fetchall()
296 print(res)
297
298 cur.execute(None, id = 10)
299 res = cur.fetchall()
300 print(res)
301
302 Statements passed to :meth:`~Cursor.prepare()` are also stored in the statement
303 cache.
291304
292305 .. _clientresultcache:
293306
1010
1111 <h1>Python and Oracle Database Tutorial: Scripting for the Future</h1>
1212
13 <img src="resources/community-py-200.png" alt="Python cx_Oracle logo">
13 <img src="resources/community-py-200.png" alt="Python cx_Oracle logo" />
1414
1515 <h2>Contents</h2>
1616
1818 <li><a href="#overview" >Overview</a></li>
1919 <li><a href="#preface" >Setup</a></li>
2020 <li><a href="#connectioninformation" >Connection Information</a></li>
21 <li><a href="#lab" >Using Python cx_Oracle 8 with Oracle Database</a></li>
21 <li><a href="#lab" >Using Python cx_Oracle 8 with Oracle Database</a>
2222 <ul>
2323 <li><a href="#connecting">1. Connecting to Oracle</a>
2424 <ul>
9898 </ul>
9999 </li>
100100 </ul>
101 </li>
101102 <li><a href="#summary" >Summary</a></li>
102103 <li><a href="#primer" >Appendix: Python Primer</a></li>
103104 <li><a href="#resources" >Resources</a></li>
118119 <p>If you are new to Python review the <a href="#primer">Appendix:
119120 Python Primer</a> to gain an understanding of the language. </p>
120121
122 <p>When you have finished this tutorial, we recommend reviewing the <a
123 href="http://cx-oracle.readthedocs.org/en/latest/index.html" >cx_Oracle
124 documention</a>. </p>
125
121126 <h2><a name="preface">Setup</a></h2>
122127
123128 <p>These cx_Oracle tutorial instructions can be found <a href="https://oracle.github.io/python-cx_Oracle/samples/tutorial/Python-and-Oracle-Database-Scripting-for-the-Future.html" >here</a>. The files used in them can be found in the <a href="https://github.com/oracle/python-cx_Oracle/tree/master/samples/tutorial" >cx_Oracle GitHub repository</a>.</p>
126131
127132 <ol>
128133 <li><p><a target="_blank" href="https://www.python.org/">Python</a>. Version 3.6 (or later) is preferred.</p></li>
129 <li><p>cx_Oracle version 7.3, or version 8, or later.</p>
134 <li><p>cx_Oracle version 7.3, or version 8, or later.</p></li>
130135 <li><p>Oracle Client libraries.</p>
131136 <ul>
132137 <li><a target="_blank" href="https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#installing-cx-oracle-on-linux">Linux</a></li>
156161
157162 <h2><a name="connectioninformation">Connection Information</a></h2>
158163
159 <p>The database connection information is set in two files:
164 <p>Database credentials and the connection string are set in two files:</p>
165
160166 <ul>
161 <li>db_config.py which is imported by the other Python modules.</li>
162 <li>db_config.sql which is used by the other SQL scripts.</li>
167 <li><p>db_config.py which is imported by the other Python modules.</p></li>
168 <li><p>db_config.sql which is used by the other SQL scripts.</p></li>
163169 </ul>
164 </p>
165170
166171 <p>The username is "pythonhol" with
167 the password "welcome". The connect string is "localhost/orclpdb1".
168 .</p>
172 the password "welcome". The connect string is "localhost/orclpdb1".</p>
169173
170174 <p>If your database is not local, or has a different service, you will need to
171175 modify the connection information in these two files. If you are installing
184188 <ul>
185189 <li>
186190 <h3><a name="connecting">1. Connecting to Oracle</a></h3>
191
192 <p>You can connect from Python to a local or remote database. <i>Documentation
193 link for further reading: <a
194 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html"
195 >Connecting to Oracle Database</a></i>.</p>
196
187197 <ul>
188198 <li>
189199 <h4>1.1 Review the connection credentials</h4>
415425
416426 <li><h3><a name="pooling">2. Connection Pooling</a></h3>
417427
428 <p>Connection pooling is important for performance when applications
429 frequently connect and disconnect from the database. Pooling also gives
430 the best support for Oracle high availability features. <i>Documentation
431 link for further reading: <a
432 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#connection-pooling"
433 >Connection Pooling</a></i>.</p>
434
435
418436 <ul>
419 <li> <h4>2.1 Connection pooling</h4>
437 <li> <h4>2.1 Connection pooling</h4>
420438
421439 <p>Review the code contained in <code>connect_pool.py</code>:</p>
422440 <pre>
565583 <table cellspacing="0" cellpadding="30" border="0" >
566584 <tr>
567585 <td>
568 <img width="400" src="resources/python_nopool.png" >
569 <p><center><strong>Without DRCP</strong></center></p>
586 <img width="400" src="resources/python_nopool.png" alt="Picture of 3-tier application architecture without DRCP showing connections from multiple application processes each going to a server process in the database tier" />
587 <div align="center"><p><strong>Without DRCP</strong></p></div>
570588 </td>
571589 <td>
572 <img width="400" src="resources/python_pool.png" >
573 <p><center><strong>With DRCP</strong></center></p>
590 <img width="400" src="resources/python_pool.png" alt="Picture of 3-tier application architecture with DRCP showing connections from multiple application processes going to a pool of server process in the database tier" />
591 <div align="center"><p><strong>With DRCP</strong></p></div>
574592 </td>
575593 </tr>
576594 </table>
708726
709727 </li>
710728 </ul>
729 </li>
711730
712731 <li><h3><a name="fetching">3. Fetching Data</a> </h3>
732
733
734 <p>Executing SELECT queries is the primary way to get data from Oracle
735 Database. <i>Documentation link for further reading: <a
736 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/sql_execution.html"
737 >SQL Queries</a></i>.</p>
713738
714739 <ul>
715740 <li><h4>3.1 A simple query</h4>
717742 <p>There are a number of functions you can use to query an Oracle
718743 database, but the basics of querying are always the same:</p>
719744
720 <p>1. Parse the statement for execution.<br />
745 <p>1. Execute the statement.<br />
721746 2. Bind data values (optional).<br />
722 3. Execute the statement.<br />
723 4. Fetch the results from the database.</p>
747 3. Fetch the results from the database.</p>
724748
725749 <p>Review the code contained in <code>query2.py</code>:</p>
726750
752776
753777 </li>
754778
755 <li><h4>3.2 Using fetchone()</h3>
779 <li><h4>3.2 Using fetchone()</h4>
756780
757781 <p>When the number of rows is large, the <code>fetchall()</code>
758782 call may use too much memory.</p>
953977 <p>If you know a query only returns a few records,
954978 decrease the arraysize from the default to reduce memory
955979 usage.</p>
956
957 </ul>
980 </li>
981 </ul>
958982
959983 </li>
960984
961985 <li><h3><a name="binding">4. Binding Data</a></h3>
962986
963 <p>Bind variables enable you to re-execute statements with new data
964 values, without the overhead of reparsing the statement. Bind
965 variables improve code reusability, and can reduce the risk of SQL
966 injection attacks.</p>
987 <p>Bind variables enable you to re-execute statements with new data values
988 without the overhead of re-parsing the statement. Binding improves code
989 reusability, improves application scalability, and can reduce the risk of SQL
990 injection attacks. Using bind variables is strongly recommended.
991 <i>Documentation link for further reading: <a
992 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/bind.html" >Using
993 Bind Variables</a></i>.</p>
967994
968995 <ul>
969996
970 <li><h4>4.1 Binding in queries</h3>
997 <li><h4>4.1 Binding in queries</h4>
971998
972999 <p>Review the code contained in <code>bind_query.py</code>:</p>
9731000
9781005 con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)
9791006 cur = con.cursor()
9801007
981 cur.prepare("select * from dept where deptno = :id order by deptno")
982
983 cur.execute(None, id = 20)
1008 sql = "select * from dept where deptno = :id order by deptno"
1009
1010 cur.execute(sql, id = 20)
9841011 res = cur.fetchall()
9851012 print(res)
9861013
987 cur.execute(None, id = 10)
1014 cur.execute(sql, id = 10)
9881015 res = cur.fetchall()
9891016 print(res)
9901017 </pre>
9911018
992 <p>The statement contains a bind variable "<code>:id</code>"
993 placeholder. The statement is only prepared once but executed
994 twice with different values for the <code>WHERE</code>
995 clause.</p>
996
997 <p> The special symbol "<code>None</code>" is used in place of
998 the statement text argument to <code>execute()</code> because
999 the <code>prepare()</code> method has already set the
1000 statement. The second argument to the <code>execute()</code>
1001 call can be a sequence (binding by position) or a dictionary (binding
1002 by name) or an arbitrary number of named arguments (also binding by
1003 name), which is what has been done in this example. In the first execute
1004 call, this dictionary has the value 20 for the key of "id". The second
1005 execute uses the value 10. </p>
1019 <p>The statement contains a bind variable "<code>:id</code>" placeholder.
1020 The statement is executed twice with different values for the
1021 <code>WHERE</code> clause.</p>
10061022
10071023 <p>From a terminal window, run:</p>
10081024
10101026
10111027 <p>The output shows the details for the two departments.</p>
10121028
1029 <p>An arbitrary number of named arguments can be used in an
1030 <code>execute()</code> call. Each argument name must match a bind
1031 variable name. Alternatively, instead of passing multiple arguments you
1032 could pass a second argument to <code>execute()</code> that is a sequence
1033 or a dictionary. Later examples show these syntaxes.</p>
1034
1035 <p>cx_Oracle uses Oracle Database's Statement Cache. As long as the
1036 statement you pass to <code>execute()</code> is in that cache, you can use
1037 different bind values and still avoid a full statement parse. The
1038 statement cache size is configurable for each connection. To see the
1039 default statement cache size, edit <code>bind_query.py</code> and add a
1040 line at the end:</p>
1041
1042 <pre>
1043 print(con.stmtcachesize)
1044 </pre>
1045
1046 <p>Re-run the file.</p>
1047
1048 <p>In your applications you would set the statement cache size to the
1049 number of unique statements commonly executed.</p>
1050
10131051 </li>
1014 <li><h4>4.2 Binding in inserts</h3>
1052
1053 <li><h4>4.2 Binding in inserts</h4>
10151054
10161055 <p>Review the code in <code>bind_insert.sql </code> creating a table
10171056 for inserting data:</p>
10661105
10671106 </li>
10681107
1069 <li><h4>4.3 Batcherrors</h3>
1108 <li><h4>4.3 Batcherrors</h4>
10701109
10711110 <p>The Batcherrors features allows invalid data to be identified
10721111 while allowing valid data to be inserted.</p>
11401179
11411180 </li>
11421181
1143 <li><h4>4.4 Binding named objects</h3>
1182 <li><h4>4.4 Binding named objects</h4>
11441183
11451184 <p>cx_Oracle can fetch and bind named object types such as Oracle's
11461185 Spatial Data Objects (SDO).</p>
11821221 cur.execute("""begin
11831222 execute immediate 'drop table testgeometry';
11841223 exception when others then
1185 if sqlcode <> -942 then
1224 if sqlcode &lt;&gt; -942 then
11861225 raise;
11871226 end if;
11881227 end;""")
12991338 <p>The <code>gettype()</code> and <code>newobject()</code> methods can
13001339 also be used to bind PL/SQL Records and Collections.</p>
13011340
1341 <p>Before deciding to use objects, review your performance goals because
1342 working with scalar values can be faster.</p>
1343
13021344 </li>
13031345 </ul>
13041346
13111353 PL/SQL lets all database applications reuse logic, no matter how the
13121354 application accesses the database. Many data-related operations can
13131355 be performed in PL/SQL faster than extracting the data into a
1314 program (for example, Python) and then processing it.</p>
1356 program (for example, Python) and then processing it. <i>Documentation link
1357 for further reading: <a
1358 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/plsql_execution.html"
1359 >PL/SQL Execution</a></i>.</p>
13151360
13161361 <ul>
1317 <li><h4>5.1 PL/SQL functions</h3>
1362 <li><h4>5.1 PL/SQL functions</h4>
13181363
13191364 <p>Review <code>plsql_func.sql</code> which creates a PL/SQL
13201365 stored function <code>myfunc()</code> to insert a row into a new
13641409
13651410 </li>
13661411
1367 <li><h4>5.2 PL/SQL procedures</h3>
1412 <li><h4>5.2 PL/SQL procedures</h4>
13681413
13691414 <p>Review <code>plsql_proc.sql</code> which creates a PL/SQL procedure
13701415 <code>myproc()</code> to accept two parameters. The second parameter
14161461
14171462 <li><h3><a name="handlers">6. Type Handlers</a></h3>
14181463
1464 <p>Type handlers enable applications to alter data that is fetched from, or sent
1465 to, the database. <i>Documentation links for further reading: <a
1466 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/sql_execution.html#changing-fetched-data-types-with-output-type-handlers"
1467 >Changing Fetched Data Types with Output Type Handlers</a> and <a
1468 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/bind.html#changing-bind-data-types-using-an-input-type-handler"
1469 >Changing Bind Data Types using an Input Type Handler</a></i>.</p>
1470
14191471 <ul>
14201472 <li>
14211473 <h4>6.1 Basic output type handler</h4>
15781630 cur.execute("""begin
15791631 execute immediate 'drop table testgeometry';
15801632 exception when others then
1581 if sqlcode <> -942 then
1633 if sqlcode &lt;&gt; -942 then
15821634 raise;
15831635 end if;
15841636 end;""")
16821734 <li><h3><a name="lobs">7. LOBs</a></h3>
16831735
16841736 <p>Oracle Database "LOB" long objects can be streamed using a LOB
1685 locator, or worked with directly as strings or bytes.</p>
1737 locator, or worked with directly as strings or bytes. <i>Documentation link
1738 for further reading: <a
1739 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/lob_data.html"
1740 >Using CLOB and BLOB Data</a></i>.</p>
16861741
16871742 <ul>
16881743 <li>
17081763 con.commit()
17091764
17101765 print("Querying data...")
1711 cur.prepare("select * from testclobs where id = :id")
1712 cur.execute(None, {'id': 1})
1766 cur.execute("select * from testclobs where id = :id", {'id': 1})
17131767 (id, clob) = cur.fetchone()
17141768 print("CLOB length:", clob.size())
17151769 clobdata = clob.read()
17641818 con.outputtypehandler = OutputTypeHandler</strong>
17651819
17661820 print("Querying data...")
1767 cur.prepare("select * from testclobs where id = :id")
1768 cur.execute(None, {'id': 1})
1821 cur.execute("select * from testclobs where id = :id", {'id': 1})
17691822 <strong>(id, clobdata) = cur.fetchone()
17701823 print("CLOB length:", len(clobdata))
17711824 print("CLOB data:", clobdata)</strong>
18641917
18651918 <p>Subclassing enables application to "hook" connection and cursor
18661919 creation. This can be used to alter or log connection and execution
1867 parameters, and to extend cx_Oracle functionality. </p>
1920 parameters, and to extend cx_Oracle functionality. <i>Documentation link for
1921 further reading: <a
1922 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/tracing_sql.html"
1923 >Tracing SQL and PL/SQL Statements</a></i>.</p>
18681924
18691925 <ul>
18701926 <li><h4>9.1 Subclassing connections</h4>
19692025 </li>
19702026
19712027 <li><h3><a name="aq">10. Advanced Queuing</a></h3>
2028
2029 <p>Oracle Advanced Queuing (AQ) allows messages to be passed between
2030 applications. <i>Documentation link for further reading: <a
2031 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/aq.html" >Oracle
2032 Advanced Queuing (AQ)</a></i>.</p>
2033
19722034 <ul>
19732035 <li><h4>10.1 Message passing with Oracle Advanced Queuing</h4>
19742036
19942056 dbms_aqadm.drop_queue_table('""" + QUEUE_TABLE_NAME + """');
19952057 execute immediate 'drop type """ + BOOK_TYPE_NAME + """';
19962058 exception when others then
1997 if sqlcode <> -24010 then
2059 if sqlcode &lt;&gt; -24010 then
19982060 raise;
19992061 end if;
20002062 end;""")
20932155 the <code>aq-dequeue.py</code>, <code>aq-enqueue.py</code> and
20942156 <code>aq-queuestart.py</code> files.</p>
20952157
2096
2158 </li>
20972159 </ul>
20982160 </li>
20992161
2100 </li>
2101
21022162 <li><h3><a name="soda">11. Simple Oracle Document Access (SODA)</a></h3>
21032163
2104 <p>Simple Oracle Document Access is a set of NoSQL-style APIs.
2164 <p>Simple Oracle Document Access (SODA) is a set of NoSQL-style APIs.
21052165 Documents can be inserted, queried, and retrieved from Oracle
21062166 Database. By default, documents are JSON strings. SODA APIs
2107 exist in many languages.</p>
2167 exist in many languages. <i>Documentation link for further reading: <a
2168 href="https://cx-oracle.readthedocs.io/en/latest/user_guide/soda.html" >Simple
2169 Oracle Document Access (SODA)</a></i>.</p>
21082170
21092171 <ul>
21102172
22052267
22062268 </li>
22072269
2208 </ol>
2270 </ul>
22092271
22102272 <h2><a name="summary">Summary</a></h2>
22112273 <p>In this tutorial, you have learned how to: </p>
22172279 <li>Use PL/SQL stored functions and procedures</li>
22182280 <li>Extend cx_Oracle classes</li>
22192281 <li>Use Oracle Advanced Queuing</li>
2282 <li>Use the "SODA" document store API</li>
22202283 </ul>
22212284
2285 <p>For further reading see the <a
2286 href="https://cx-oracle.readthedocs.io/en/latest/index.html" >cx_Oracle
2287 documentation</a>.</p>
22222288
22232289 <h2><a name="primer">Appendix: Python Primer</a></h2>
22242290
22252291 <p>Python is a dynamically typed scripting language. It is most
2226 often used to run command-line scripts but is also used in Web
2227 applications.</p>
2292 often used to run command-line scripts but is also used for web
2293 applications and web services.</p>
22282294
22292295 <h4>Running Python</h4>
22302296
24322498 <div class="footer"></div>
24332499 <table border="0" cellpadding="10" cellspacing="0" width="100%">
24342500 <tbody><tr>
2435 <td align="right" width="54%">Copyright &copy; 2017, 2019, Oracle and/or its affiliates. All rights reserved</td>
2501 <td align="right" width="54%">Copyright &copy; 2017, 2020, Oracle and/or its affiliates. All rights reserved</td>
24362502 </tr>
24372503 <tr><td colspan="2"></td></tr>
24382504 </tbody>
24392505 </table>
24402506
2441
2442 </div>
24432507 </body>
24442508 </html>
1111 con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)
1212 cur = con.cursor()
1313
14 cur.prepare("select * from dept where deptno = :id order by deptno")
14 sql = "select * from dept where deptno = :id order by deptno"
1515
16 cur.execute(None, id = 20)
16 cur.execute(sql, id = 20)
1717 res = cur.fetchall()
1818 print(res)
1919
20 cur.execute(None, id = 10)
20 cur.execute(sql, id = 10)
2121 res = cur.fetchall()
2222 print(res)
1818 char = chr(ord('A') + i)
1919 longString += char * 250
2020 cur.execute("insert into testclobs values (:1, :2)",
21 (i + 1, "String data " + longString + ' End of string'))
21 (i + 1, "String data " + longString + ' End of string'))
2222 con.commit()
2323
2424 print("Querying data...")
25 cur.prepare("select * from testclobs where id = :id")
26 cur.execute(None, {'id': 1})
25 cur.execute("select * from testclobs where id = :id", {'id': 1})
2726 (id, clob) = cur.fetchone()
2827 print("CLOB length:", clob.size())
2928 clobdata = clob.read()
2828 con.outputtypehandler = OutputTypeHandler
2929
3030 print("Querying data...")
31 cur.prepare("select * from testclobs where id = :id")
32 cur.execute(None, {'id': 1})
31 cur.execute("select * from testclobs where id = :id", {'id': 1})
3332 (id, clobdata) = cur.fetchone()
3433 print("CLOB length:", len(clobdata))
3534 print("CLOB data:", clobdata)