How can I access Oracle from Python?

后端 未结 9 539
傲寒
傲寒 2020-12-04 12:15

How can I access Oracle from Python? I have downloaded a cx_Oracle msi installer, but Python can\'t import the library.

I get the following error:

im         


        
9条回答
  •  不思量自难忘°
    2020-12-04 13:15

    Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:

    import cx_Oracle
    
    CONN_INFO = {
        'host': 'xxx.xx.xxx.x',
        'port': 12345,
        'user': 'SOME_SCHEMA',
        'psw': 'SECRETE',
        'service': 'service.server.com'
    }
    
    CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)
    
    QUERY = '''
        SELECT
            *
        FROM
            USER
        WHERE
            NAME = :name
    '''
    
    
    class DB:
        def __init__(self):
            self.conn = cx_Oracle.connect(CONN_STR)
    
        def query(self, query, params=None):
            cursor = self.conn.cursor()
            result = cursor.execute(query, params).fetchall()
            cursor.close()
            return result
    
    
    db = DB()
    result = db.query(QUERY, {'name': 'happy'})
    

提交回复
热议问题