如何从 cursor.description 或 select 语句生成 DDL

How to make DDL from cursor.description or a select-statement

使用cx_Oracle5.1.2、python2.7和Oracle 11g,我的情况如下:

我有一个 cx_oracle 游标连接到 DB_one 我会调用 cur_input 另一个游标连接到 DB_two 我会调用 cur_output.

在 cur_input 上执行选择后,我希望能够生成它的 DDL 以在 cur_output 上创建拟合 table,然后将数据插入此 table 来自 cur_input。问题在于创建 table.

时的数据类型和定义

在伪代码中,我想:

CREATE TABLE cur_output.schema.tablename 
          AS 
      SELECT a,b,1,2,decode(1,1,'2',2,3)
        FROM cur_input.schema.tablename
       WHERE 1=2

所有这一切都可以在没有以下条件的情况下完成:

...?

cur_input.description 中的条目似乎对此非常有用,但我不觉得 table 将 cur_input.description 中的 cx_Oracle.STRING 直接翻译成 VARCHAR2 用于output-DDL 因为 cx_Oracle.STRING 可以转换为 Oracle 的:VARCHAR2、NVARCHAR2 或 LONG (完整翻译-table: http://www.oracle.com/technetwork/articles/dsl/prez-python-queries-101587.html -- 章节: 数据类型)

提前致谢!

答案非常简单。使用 cursor.description 方式:可以明确地完成从 cx_Oracle 的类型到 Oracle 的数据类型的转换。我正在使用石器时代的文档是什么问题...

translator = { 'BINARY'         : 'RAW',\
           'BFILE'          : 'BFILE',\
           'BLOB'           : 'BLOB',\
           'CLOB'           : 'CLOB',\
           'CURSOR'         : 'CURSOR',\
           'DATETIME'       : 'DATE',\
           'FIXED_CHAR'     : 'CHAR',\
           'FIXED_UNICODE'  : 'NCHAR',\
           'INTERVAL'       : 'INTERVAL',\
           'LONG_STRING'    : 'LONG',\
           'LONG_UNICODE'   : 'LONG ',\
           'NCLOB'          : 'NCLOB',\
           'NUMBER'         : "NUMBER",\
           'OBJECT'         : 'OBJECT',\
           'ROWID'          : 'ROWID',\
           'STRING'         : 'VARCHAR2',\
           'TIMESTAMP'      : 'TIMESTAMP',\
           'UNICODE'        : "NVARCHAR2" }

str_coltype     # example:  "<type 'cx_Oracle.NUMBER'>"
cx_coltp = re.findall("\.([^\.]+)'>$", str_coltype)[0]
ora_coltp = translator[ cx_coltp ]

事实证明,这里有一些一流的文档:

http://cx-oracle.readthedocs.org/en/latest/module.html#types