cx_Oracle实现查询,修改数据库,以及对SQL语句实现参数化

本文介绍了如何使用Python的cx_Oracle库进行Oracle数据库的查询和修改操作,包括执行SQL语句及实现参数化的示例。

查询语句

Test_oracle = {
    "shengchan": {
        "test_user": {"userName": "xxx", "pwd": "xxxx", "iP": "172.xx.xxx.xxx", "dbSID": "xxx"},
    }
def search(test1,test2):
    """
    查询语句
    :param test1:参数化数据1
    :param test2:参数化数据2
    :return:
    """
    # 定义连接数据库的信息
    userName = Test_oracle["shengchan"]["test_user"]["userName"]
    pwd = Test_oracle["shengchan"]["test_user"]["pwd"]
    iP = Test_oracle["shengchan"]["test_user"]["iP"]
    dbSID = Test_oracle["shengchan"]["test_user"]["dbSID"]
    # 连接数据库
    conn = cx_Oracle.connect(userName + '/' + pwd + '@' + iP + ':xxxx/' + dbSID)
    cur = conn.cursor()  # 获取cursor
    named_params = { 'param1': test1,'param2':test2}
    sql = "SELECT * FROM test_table WHERE test_TIME = :param1 AND TYPE = :param2"
    cur.execute(sql,named_params)  # 执行sql
    data = cur.fetchall()
    return data

修改语句

Test_oracle = {
    "shengchan": {
        "test_user": {"userName": "xxx", "pwd": "xxxx", "iP": "172.xx.xxx.xxx", "dbSID": "xxx"},
    }
def update(test1,test2):
    """
    修改语句
    :param test1:参数化数据1
    :param test2:参数化数据2
    :return:
    """
    # 定义连接数据库的信息
    userName = Test_oracle["shengchan"]["test_user"]["userName"]
    pwd = Test_oracle["shengchan"]["test_user"]["pwd"]
    iP = Test_oracle["shengchan"]["test_user"]["iP"]
    dbSID = Test_oracle["shengchan"]["test_user"]["dbSID"]
    # 连接数据库
    conn = cx_Oracle.connect(userName + '/' + pwd + '@' + iP + ':xxxx/' + dbSID)
    cur = conn.cursor()  # 获取cursor
    named_params = { 'param1': test1,'param2':test2}
    sql = "UPDATE Test_table SET test_data = :param1 WHERE TYPE = :param2"
    cur.execute(sql,named_params)  # 执行sql
    # 必须使用commit(),提交事务,不然数据可能丢失
    conn.commit()
    cur.close()
    conn.close()
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值