简体   繁体   English

使用 python(cx_oracle) 连接到 oracle 数据库

[英]Connecting to oracle database using python(cx_oracle)

I am trying to connect to oracle database using cx_Oracle in python.我正在尝试使用 python 中的 cx_Oracle 连接到 oracle 数据库。 I am able to connect to the database and pull the data.我能够连接到数据库并提取数据。

Now I am trying to connect to one more database where I have to call a security procedure first and then only I can see data in the underlying tables.现在我正在尝试连接到另一个数据库,我必须首先调用一个安全过程,然后我才能看到基础表中的数据。 Can you please help me in calling the procedure by adjusting the below block of code.您能否通过调整以下代码块来帮助我调用该程序。 My procedure will be like: exec ef.applogin('1234')我的程序将是: exec ef.applogin('1234')

def connect_oracle():
    import cx_Oracle
    import pandas as pd
    ip = 'some_ip'
    port = 1521
    SID = 'some_SID'
    dsn_tns = cx_Oracle.makedsn(ip, port, SID)
    connection = cx_Oracle.connect('user_name', 'password', dsn_tns)
    #Procedure to be executed here..    
    query = """ SELECT * from table_name """
    df_ora = pd.read_sql(query, con=connection)
    return df_ora

connect_oracle()

Many thanks in advance!!提前谢谢了!!

Create def for connect by Oracle.通过 Oracle 为连接创建 def。 for execute procedure use cursor.执行程序使用 cursor。 Don't forget close connect and cursor.不要忘记关闭连接和 cursor。 Also in case exception.也以防万一。

import cx_Oracle
import pandas as pd

ip = 'some_ip'
port = 1521
SID = 'some_SID'
user_name = 'user_name'
password = 'password'
query = """ SELECT * from table_name """

def connect_oracle(ip, port, SID, user_name, password):
    dsn_tns = cx_Oracle.makedsn(ip, port, SID)
    connection = cx_Oracle.connect(user_name, password, dsn_tns)
    return connection

def get_df(conn, query):
    df_ora = pd.read_sql(query, con=conn)
    return df_ora


def execute_proc(conn, procname, param):    
    my_cursor=conn.cursor()
    my_cursor.callproc(procname, param)
    conn.commit()

def execute_func(conn, procname, param):    
    my_cursor=conn.cursor()
    out_parameter = my_cursor.var(cx_Oracle.NUMBER)
    qw = my_cursor.callfunc(procname, out_parameter)
    return qw

conn1 = connect_oracle(ip, port, SID, user_name, password)
df = get_df(conn1, query)
df.head()
execute_proc(conn1, "insert_temp", [])
execute_func(conn1, "get_version", [])

Function for test: Function 进行测试:

create or replace function get_version
return number
is
    v_version NUMBER(8) := 11;
begin
    return v_version;
end;

Procedure for test:测试程序:

create table temp (clm number);
create or replace procedure insert_temp
is
    v_version NUMBER(8) := 11;
begin
    insert into temp(clm) values(v_version);
end;
select *  from temp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM