error when connecting oracle in python using cx_Oracle

前端 未结 4 1823
耶瑟儿~
耶瑟儿~ 2021-01-19 16:29

I was trying to connect oracle database using python like below.

import cx_Oracle
conn = cx_Oracle.connect(\'user/password@host:port/database\')
4条回答
  •  难免孤独
    2021-01-19 17:22

    Here is the full program to connect Oracle using python. First, you need to install cx_Oracle. to install it fire the below command.

    pip install cx_Oracle

    import cx_Oracle
    
    def get_databse_coonection():
        try:
            host='hostName'
            port ='portnumber'
            serviceName='sid of you database'
            user = 'userName'
            password = 'password'
            dns = cx_Oracle.makedsn(host,port,service_name=serviceName)
            con = cx_Oracle.connect(user, password, dns)
            cursor = con.cursor()   
            query ="select * from table"
            cursor.execute(query)
            for c in cursor:
                print(c)
        except cx_Oracle.DatabaseError as e: 
            print("There is a problem with Oracle", e) 
        finally:
            if cursor:
                cursor.close()
            if con:
                con.close()
    
    get_databse_coonection()

提交回复
热议问题