【python oracle】Python3 连接oracle 教程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013421629/article/details/79974155

1、安装要求
安装Python3以上版本,python2.7不要用

2、python环境变量配置

把 python的安装目录加入环境变量中的path
把python安装目录下的Scripts目录加入环境变量中的path 如: E:\laidefa\Scripts 把这个目录加入环境变量中的path

3、需要安装库

打开cmd命令安装软件库

Pip install cx_Oracle

4、把解压后的oracle_client文件夹放在一个目录下,并把它加入环境变量中的path目录下。

5、开启openvpn,以管理员身份运行,若连接不成功,检查网络,重启下试试。

6、测试例子

# encoding: utf-8

import  cx_Oracle as cx

import pandas.io.sql as sql
# --------------------------------------
# 建立数据库连接
# --------------------------------------
ip = 'XXXXXXXXXXXXXXX'
port = XXXXX
db = 'XXXXX'
username = "XXXXXXXXXXXXXXXXXX"
pwd = "XXXXXXXXXXXXX"

dsn = cx.makedsn(ip, port, db)
connection = cx.connect(username, pwd, dsn)

print("oracle版本:", connection.version)
cursor = connection.cursor()

# 获取用于训练和测试的元数据

meta_data = sql.read_sql(
    """
    select race_id from view_race_s_o_history m
    where rownum <= 5
    """, connection)

print(meta_data)
meta_data.dropna(axis=0, how='any', inplace=True)

meta_data.drop_duplicates()

cursor.close()

connection.close()

7、运行成功效果

E:\laidefa\python.exe "E:/Program Files/pycharmproject/project_2018/读取oracle数据.py"
oracle版本: 12.2.0.1.0
   RACE_ID
0  2578628
1  2578634
2  2578550
3  2578586
4  2574294

Process finished with exit code 0

8、代码模块2写成函数:

# encoding: utf-8

"""
python 连接oracle
"""

import  cx_Oracle as cx
import pandas.io.sql as sql


def connection_oracle(string):
    host = 'XXXXXXXXXXX'
    port = 1521
    database = 'dev'
    username = "XXXXXXXXXXX"
    password = "XXXXXXXXXXXXX"

    dsn = cx.makedsn(host, port, database)
    connection = cx.connect(username, password, dsn)
    cursor = connection.cursor()

    data=sql.read_sql(string,connection)
    connection.commit()
    cursor.close()
    connection.close()
    return data




string_sql="""

  select  * from KKTRIBE_SUBJECT

"""

data=connection_oracle(string_sql)

print(data)
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页