Cx_Oracle and the data source paradigm

There is a Java paradigm for accessing a database implemented in Java DataSource. This object creates a useful abstraction around creating database connections. The object DataSourcesaves the database configuration, but upon request it will create connections to the database. This allows you to save the entire database configuration and initialization code in one place and simplify changing the database implementation or use the mock database for testing.

I am currently working on a Python project that uses cx_Oracle. In cx_Oracle, you get the connection directly from the module:

import cx_Oracle as dbapi
connection = dbapi.connect(connection_string)
# At this point I am assuming that a real connection has been made to the database.
# Is this true?

I am trying to find a parallel with DataSourcein cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this was the right thing to do in Python.

+3
source share
4 answers

You will find relevant information on how to access the database in Python viewing PEP-249: API Specification v2.0 base Python data , cx_Oracleconforms to this specification, as well as many database drivers for Python.

Connection , . , SQLAlchemy, , SQLAlchemy ORM, SQL.

- , SQLAlchemy , , , Elixir, SQLAlchemy .

+3

, Python "" , , , .

DataSource ( - Java) SQLAlchemy ( - ) , - .

, .

+1

, Python .

, , , .

if database == SYBASE:
    import Sybase
    conn = Sybase.connect('sybasetestdb','mh','secret')
elif database == POSTRESQL:
    import pgdb
    conn = pgdb.connect('pgtestdb:mh:secret')
elif database == ORACLE:
    import cx_Oracle
    conn = cx_Oracle.connect("mh/secret@oracletestdb")

curs=conn.cursor()
curs.execute('select a,b from testtable')
for row in curs.fetchall():
    print row

( , , , , dbconnection, .)

0
source

I just pulled it in and wrote it myself. This allowed me to add things like database abstraction (Oracle / MySQL / Access / etc), adding a log, handling error with transaction rollbacks, etc.

0
source

Source: https://habr.com/ru/post/1712954/


All Articles