Oracle with Python - 如何检查列是否已存在?

问题描述 投票:1回答:1

我正在尝试使用python从属性列表创建Oracle表。遗憾的是,我有多个具有相同名称的属性,因此我无法将它们添加到表中。此外,我不希望我的程序因此而停止。现在我正在尝试这个解决方案:

connection = cx_Oracle.connect('user/password')
cursor = connection.cursor()

if not tableExists(connection, 'TableName'):
first_column_name = next(iter(attributes), None)
query_table = 'CREATE TABLE TableName ("{}" VARCHAR2(255))'.format(first_column_name)
cursor.execute(query_table)


for attribute in attributes[1:]:
    query_column= '''
    DECLARE
        v_column_exists number := 0;  
    BEGIN
        Select count(*) into v_column_exists
            from user_tab_cols
            where upper(column_name) = "{}"
            and upper(table_name) = 'TableName';

        if (v_column_exists = 0) then
            execute immediate 'alter table TableName add ("{}" VARCHAR2(255)))';
        end if;
    end;
    '''.format(attribute, attribute)

    cursor.execute(query_column)

我已经粘贴了this answer.中的长查询代码。该表是按照预期创建的第一个属性,但是我会开始添加更多列:

Traceback (most recent call last):
File "main.py", line 52, in <module>
cursor.execute(query_column)
cx_Oracle.DatabaseError: ORA-06550: line 7, column 41:
PL/SQL: ORA-00904: "Order count [A221]": invalid identifier
ORA-06550: line 5, column 9:
PL/SQL: SQL Statement ignored

我错过了什么?

python sql database cx-oracle oracle18c
1个回答
2
投票

我建议简单地构建create table语句,而不是构建表,然后改变它以向其添加列!

您可以使用以下代码删除列表中的重复项:

listWithoutDups = list(dict.fromkeys(listWithDups))

然后,您可以按如下方式构建语句:

columns = ['"%s" varchar2(255)' % n for n in listWithoutDups]
sql = "create table SomeTableName (%s)" % ",".join(columns)
cursor.execute(sql)

你会注意到我在列名称周围加了双引号 - 如果你想创建不符合Oracle标准的列(包括特殊字符,空格等),这是必要的,但要注意,这也会使名称区分大小写,当您对表执行任何操作时,您还需要指定引号。

© www.soinside.com 2019 - 2024. All rights reserved.