python中cx_Oracle的操作

来源:互联网 发布:西门子plc的编程技巧 编辑:程序博客网 时间:2024/05/23 01:20

大型软件的测试过程中,免不了要对Oracle进行查询或者操作,网上也有很多例子,但个人认为都不是特别好,对测试的帮助不大,索性写了一个供大家参考

 

def oracle_connect_cursor():    '''    oracle_connect_cursor    '''    dsn_tns = cx_Oracle.makedsn(ip, port,数据库名 )    connection = cx_Oracle.connect(用户名, 密码, dsn_tns)    cursor = connection.cursor()    return cursordef execute_sql(sCommand):        '''        execute_sql
        '''        db =oracle_connect_cursor()        db.execute(sCommand)        if 'select' not in sCommand[6]:            db.execute('commit')        if 'select' in sCommand[6]:            sResult = db.fetchall()            print sResult            # If did not get and value, it will return None            # if not len(sResult):            if not sResult:  # if the sResult is empty, the sResult's value is false                sResult = None            return sResult

 

以上代码中设置了检查传进来的命令的前6个字母是不是select,如果是select 则返回查询结果,否则操作完了就提交。将上述代码插入到你的代码后,可以采用如下方式引用:

 

sCommand=('update table_name set key=key-120 where name=\'%s\'' %var1)execute_sql(sCommand)

这段代码是更新数据库的代码。就是将table_name 中name等于var1的key值减少120

而这个过程中可以直接引用 execute_sql(sCommand) 来操作,是不是很简单啊?

 

下面再看看查找的例子

sCommand=('select key from table_name where name=\'%s\'' %var1)key_value=execute_sql(sCommand)

请根据上面的代码结合起来看这段代码:这段代码的命令式以select开头的,所以必然要返回信息。所以通过这样的方式,可以返回执行命令的结果,不过值得提醒的是:请使用

print type(key_value)


来查看一下吧,然后我想你就知道怎么操作了。


原创粉丝点击