python oracle数据库脚本导出

import os,sys
import cx_Oracle


def search(sqlstr,**argv):
    cursor.execute(sqlstr,argv)
    return cursor.fetchall()


def getcols(tabname):
    cols=search('select column_name from user_tab_columns where table_name=:V1 order by column_id',V1=tabname)
    s=''
    for col in cols:
        s=s+','+col[0]
    return s[1:]
   
if __name__ == '__main__':
    if sys.argv.__len__() != 3:
        print """Please Input Connect Arguments And SQL Export Directory.\nEx: oracle_export.py aa/bb@testdb e:\sqlfile"""
        exit(-1)
    desdir = sys.argv[2] .
    if not os.path.isdir(desdir):
        print "Target directory is not Exists."
        exit(-3)
       
    try:
        conn = cx_Oracle.Connection(sys.argv[1].split('/')[0],sys.argv[1].split('/')[1].split('@')[0],sys.argv[1].split('@')[-1])
    except cx_Oracle.DatabaseError,strerr:
        print "Connect DataBase Failure. \n%s" % strerr
        exit(-2)
       
    cursor = conn.cursor()

    objs=search('select distinct type,name from user_source')
   

    for obj in objs:
        f=open(os.path.join(desdir,obj[0].replace(' ','_')+' '+obj[1])+'.sql','w')
        str=search('select text from user_source where name=:v1 and type=:v2 order by line',V1=obj[1],V2=obj[0])
        f.write('CREATE OR REPLACE\n')
        for i in str:
            f.write(i[0])
        f.write('/\n')
        f.close()
   

    objs=search('select view_name,text from user_views')
    for obj in objs:
        f=open(os.path.join(desdir,'VIEW '+obj[0])+'.sql','w')
        f.write('CREATE OR REPLACE\n')
        f.write('VIEW ( '+getcols(obj[0])+' ) AS\n')
        f.write(obj[1])
        f.write('/\n')
        f.close()
   
    cursor.close()
    conn.close()

你可能感兴趣的:(oracle,python,脚本,OS,F#)