通过python连接Oracle
一、安装cx_Oracle
pip install cx_Oracle即可
二、安装instantclient
windows方式:
第一次使用需要注册即可下载资源
1.下载windows对应配置的即可,我这里下载的是instantclient_11_2
2.环境配置
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
os.environ['TNS_ADMIN'] = 'D:\program\instantclientx64_jb51\instantclient_11_2'
os.environ['Path'] = 'D:\program\instantclientx64_jb51\instantclient_11_2'
linux方式:
1.下载linux对应配置的即可,我这里下载的是instantclient_18_5
18.3以后不用建软链接,已经存在。
2.以上已经完成了instantclient下载,如果需要使用Oracle命令行查询的话还需要安装 instantclient-sqlplus-linux工具,同样是官网下载相应版本
3.下载完成后将它们两个解压在同一个文件夹里,如下
4.目录network/admin新建tnsnames.ora,内容如下:
XY =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.6.175)(PORT = 2261))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = lsxy_sn)))
修改1,4,8行,与Oracle配置一样
5.环境配置
vi /etc/profile
添加以下内容
export ora_home=/home/lsxy #instantclient_18_5所在目录
export PATH=$PATH:$ora_home/instantclient_18_5
export ORACLE_BASE=$ora_home
export ORACLE_HOME=$ORACLE_BASE/instantclient_18_5
export LD_LIBRARY_PATH=$ORACLE_HOME
export NLS_LANG="SIMPLIFIED CHINESE_CHINA.ZHS16GBK"
source /etc/profile
6.远程连接oracle
命令行输入:
sqlplus 用户名/密码@//ip:port/orcl
即可启动oracle操作行命令
三、python链接Oracle
# 查询表
db = cx_Oracle.connect('用户名', '密码', 'ip:port/orcl')
cr = db.cursor()
# 小时粒度人流信息表
sql = "select * from table"
cr.execute(sql)
rs = cr.fetchall()
old_data = pd.DataFrame(rs)
#写入表(下面是整体写入,也可insert into单行写入)
y_weight = y_weight.values.tolist()
sql = '''insert into F_HX_SCENIC_FUTURE_STATISTICS
(AREA_ID,subscriber_count,statistic_time,created_time)
values (:1,:2,:3,:4)
'''
cr.executemany(sql, y_weight)
db.commit()
cr.close()
db.close(
参考博客:
https://www.cnblogs.com/daisy89/p/5307727.html