2017-06-21 108 views
0

Im新的python。这里是我的问题 我有两个Oracle数据库在两个不同的位置(目标和源)。一个在IP1(目标)和另一个在IP2(源) 我需要做的是将IP2中的一个表复制到IP1中。类似CREATE TABLE ... AS使用python在另一个数据库上创建一个类似的表格

我试图创建两个光标像下面

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

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

看来我不能提供一个游标执行,以执行另一个光标的输出。 有没有办法做到这一点?任何专家都可以对此有所了解。

+0

为什么不直接使用CREATE TABLE AS .. SELECT * FROM ..?创建一个到IP2的IP链接到IP1。不需要编码。 – OldProgrammer

+0

我需要做的是将一组表IP2迁移到IP1。这是由不同的过程调用的。还需要更改需要动态迁移的表格。这就是我使用python脚本的原因。我不认为创建数据库链接是可行的 – Zarco

回答

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 + ")" 
相关问题