python3连接Oracle数据库

1、下载cx_Oracle,下载地址为:https://pypi.org/project/cx-Oracle/#files

下载时注意选择python版本以及对应的操作系统型号

 

2、安装cx_Oracle:

cmd到cx_Oracle路径

执行pip install xxx.whl,执行报如下报错,原因:对应cx_Oracle下载版本有误,重新下载一个版本

cx_Oracle-8.2.1-cp36-cp36m-win32.whl is not a supported wheel on this platform.

重新执行:pip install cx_Oracle-8.2.1-cp36-cp36m-win_amd64.whl,安装成功,提示“Successfully installed cx-Oracle-8.2.1”,见下图

3、使用cx_Oracle与Oracle数据库交互

用例1(查询)

import cx_Oracle
#连接数据库,下面括号里内容根据自己实际情况填写
conn = cx_Oracle.connect('tjzsyl/tjzsyl@192.168.129.221:1521/ora11g')
# 使用cursor()方法获取操作游标
cursor = conn.cursor()
#使用execute方法执行SQL语句
result=cursor.execute('Select * from ic89')
#使用fetchone()方法获取一条数据
#data=cursor.fetchone()
 
#获取所有数据
all_data=cursor.fetchall()
 
#获取部分数据,8条
#many_data=cursor.fetchmany(8)
 
print (all_data)
cursor.close()
conn.close()

用例2(插入数据)

def try_to_connect_and_insert():
    username="tjzsyl"
    userpwd="tjzsyl"
    host="192.168.129.221"
    port=1521
    dbname="ora11g"
    insertCount = 0
    totalCount = 1
    dsn=cx_Oracle.makedsn(host,port,dbname)
    try:
        connection=cx_Oracle.connect(username,userpwd,dsn)
        connection.autocommit=True
        sql="insert into bec7(BAZ498,BAZ002,BAA502,BAA504) VALUES(20210622001,20210622001,'PYTHON测试','PYTHON测试oracle插入数据')"
        cursor=connection.cursor()
        for i in range(totalCount-insertCount):
            insertCount=i
            cursor.execute(sql)
        print(totalCount)
        cursor.close()
        connection.close()
    except Exception as e:
        print(e)
        print(totalCount)
        
if __name__ == '__main__':
    #try_to_connect_and_select()
    try_to_connect_and_insert()

用例3(update)

def try_to_connect_and_update():
    username="tjzsyl"
    userpwd="tjzsyl"
    host="192.168.129.221"
    port=1521
    dbname="ora11g"
    insertCount = 0
    totalCount = 1
    dsn=cx_Oracle.makedsn(host,port,dbname)
    try:
        connection=cx_Oracle.connect(username,userpwd,dsn)
        connection.autocommit=True
        sql="update bec7 set baa502='python测试二版' where baz498=20210622001"
        cursor=connection.cursor()
        for i in range(totalCount-insertCount):
            insertCount=i
            cursor.execute(sql)
        print(totalCount)
        cursor.close()
        connection.close()
    except Exception as e:
        print(e)
        print(totalCount)

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TryTestwonderful

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值