cx_Oracle链接oracle数据库

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created on 2018-1-20
# @author: Ethan
import base64
import os
import cx_Oracle

import writelog

_get_abs_path = lambda path: os.path.normpath(os.path.join(os.path.dirname(__file__), path))
file_dir = os.path.split(_get_abs_path(__name__))[0]


def get_database_connection():
    v_ip, v_port = '', ''

    with open(os.path.join(file_dir, "_conf.txt"), "r") as f:
        while True:
            line = f.readline().replace("\n", "").replace("\r", "")
            if not line:
                break
            if "DATABASE_IP" in line:
                v_ip = line[line.index(":") + 1:]
            if "DATABASE_PORT" in line:
                v_port = line[line.index(":") + 1:]
        f.close()

    try:
        dsn = cx_Oracle.makedsn(v_ip, v_port, "database")
        return cx_Oracle.connect("username, "password", dsn)
    except Exception as error_info:
        writelog.write_log("连接数据库失败", error_info.__str__())
        return None


if __name__ == '__main__':
    conn = get_database_connection()

    if conn:
        print(u'连接数据库成功')
        cursor = conn.cursor()
        try:
            # cursor.execute(""" insert into a(ip_address,web_id,version,content)
            #     values(:ip, :id, :ver, :content) """, {"ip":  LOCAL_IP, "id": query_type, "ver": VERSION, "content": query_content})
            # conn.commit()
            cursor.execute(""" select * from b where rownum < 3""")
            while True:
                row = cursor.fetchone()
                if row is None:
                    break
                f_name = str(row[1]).decode("gbk")
                print(f_name)
        except Exception as e:
            print(u'查询出错!' + e.__str__())
        finally:
            cursor.close()

        try:
            conn.close()
            print(u'断开数据库成功!')
        except Exception as e:
            print(u'断开数据库失败!' + e.__str__())
    else:
        print(u'连接数据库失败!')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值