python 查询 Oracle

如下代码片段使用 cx_Oracle 查询 Oracle DB.

import cx_Oracle

def query(conn_params, sql, named_params = None):
conn = None
ret_list = []
try:
    conn = cx_Oracle.connect(conn_params)
    try:
        cur = conn.cursor()

        if named_params is None:
            cur.execute(sql)
        else:
            cur.execute(sql, named_params)
        
        return cur.fetchall()
    finally:
        cur.close()
finally:
    if conn is not None:
        conn.close()

调用方式:

named_params = {"name":"eric", "age":18}
sql = "SELECT * FROM user WHERE name = :name and age = :age"
conn_url = "app_read/app_read@db.tianxiaohui.com:1521/APP"

results = query(conn_url, sql, named_params)
print(results)

results = query(conn_url, "SELECT * FROM user")
print(results)

标签: none

添加新评论