使用python从另一个DB上的一个DB创建一个类似的表

时间:2017-06-21 12:14:46

标签: python sql oracle cx-oracle

我是python的新手。这是我的问题 我在两个不同的位置(目标和源)有两个Oracle数据库。一个在IP1(目标),另一个在IP2(源) 我需要做的是将IP2中的表格复制到IP1。与CREATE TABLE ... AS

类似

我尝试创建两个游标,如下面的

curTarget = db_con_target.cursor() -->IP1
curSource = db_con_source.cursor() -->IP2

curTarget.execute("""create table TargetTable as (""",curSource.execute("select * from SourceTable"))

似乎我无法提供游标执行的输出来执行另一个游标。 有没有办法做到这一点 ?任何专家都能对此有所了解。

1 个答案:

答案 0 :(得分:0)

似乎没有办法将游标的输出提供给另一个游标。 所以我所做的是操纵游标的输出并手动创建CREATE TABLE查询。 有效。 对于前:     curSource = db_con_source.cursor()

    describeQuery = "SELECT * FROM " + tableName.strip() + " WHERE 1=0"
    createTableQuery = "CREATE TABLE " + tableName.strip() + " ("

    #print describeQuery    
    curSource.execute(describeQuery)

    for desc in curSource.description:
            print desc
            column_name = desc[0]

            if desc[6]== 0 :
                    nullable = "NOT NULL"
            else :
                    nullable = "NULL"

            if desc[1].__name__ == "STRING" :
                    data_type = "VARCHAR2"
                    data_length = desc[3]

                    #creating the query here for string types since it does not involve the precision
                    createTableQuery = createTableQuery + " " + column_name + " " + data_type + "(" + str(data_length) + ") " + nullable + ", "
            elif desc[1].__name__ == "NATIVE_FLOAT" :
                    data_type = "BINARY_DOUBLE"
                    createTableQuery = createTableQuery + " " + column_name + " " + data_type + " " +  nullable + ", "
            else :
                    data_type = "NUMBER"
                    data_length = desc[4]
                    precision = desc[5]

                    if data_length == 0:
                            createTableQuery = createTableQuery + " " + column_name + " " + data_type + " " +  nullable + ", "
                    else:
                            #creating the query here for int types since it does invole both length and the precision
                            createTableQuery = createTableQuery + " " + column_name + " " + data_type + "(" + str(data_length) + "," + str(precision) + ") " + nullable + ", "

    #remove last two characters : space and comma 
    createTableQuery = createTableQuery[:-2]
    createTableQuery = createTableQuery + " )"