Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oracle with Python-如何检查列是否已经存在?_Python_Sql_Database_Cx Oracle_Oracle18c - Fatal编程技术网

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

Oracle with Python-如何检查列是否已经存在?,python,sql,database,cx-oracle,oracle18c,Python,Sql,Database,Cx Oracle,Oracle18c,我正试图用python从属性列表中创建一个Oracle表。遗憾的是,我有多个同名属性,因此无法将它们添加到表中。我也不希望我的程序因此而停止。 现在我正在尝试这个解决方案: connection = cx_Oracle.connect('user/password') cursor = connection.cursor() if not tableExists(connection, 'TableName'): first_column_name = next(iter(attributes

我正试图用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)
我粘贴了来自表的长查询代码,该表按预期使用第一个属性创建,但由于我将开始添加更多列,我得到:

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
回溯(最近一次呼叫最后一次):
文件“main.py”,第52行,在
cursor.execute(查询列)
cx_Oracle.DatabaseError:ORA-06550:第7行第41列:
PL/SQL:ORA-00904:“订单计数[A221]”:无效标识符
ORA-06550:第5行第9列:
PL/SQL:SQL语句被忽略

我缺少什么?

我建议只构建CREATETABLE语句,而不是构建表,然后对其进行修改以向其中添加列

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

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标准的列(包括特殊字符、空格等),这是必要的,但请注意,这也会使名称区分大小写,并且在表上执行任何操作时也需要指定引号。

,好先生!是的,今天早上我意识到我应该在用一个命令创建整个表之前做好一切准备。感谢dict.fromkeys提示,我用了更长、更繁琐的逻辑实现了它,但这一个更优雅。很高兴能提供帮助!