Python 对Oracle的操作

简单的封装

def Oracle_Exec(SqlStr):
    "Execute oracle command"
    conn = cx_Oracle.connect(DB_UserName, DB_UserPwd, DB_ConnectStr)    
    cursor = conn.cursor()
    try:
        cursor.execute(SqlStr)
        conn.commit()
        return True    
    except:
        conn.rollback()
        print "Exec sql failed: %s" % SqlStr
        return False
    finally:        
        cursor.close()
        conn.close()
        
def Oracle_Query(SqlStr, debug = 0):
    "Execute oracle query, and return datalist"
    datalist = []   
    conn = cx_Oracle.connect(DB_UserName, DB_UserPwd, DB_ConnectStr)
    cursor = conn.cursor()
    try:
        cursor.execute(SqlStr)    
        while 1:     
            rs = cursor.fetchone()
            if rs == None:
                break
            datalist.append(rs)
        if debug:
            fieldnames = []
            for field in cursor.description:
                fieldnames.append(field[0])
            print fieldnames
            print datalist
            print "Query success!"            
    except:
        print "Exec sql failed: %s" % SqlStr         
    finally:        
        cursor.close()
        conn.close()
        return datalist     


你可能感兴趣的:(oracle,sql,python,command,query)