简体   繁体   中英

Oracle with Python - How to check if column already exists?

I'm trying to create an Oracle table from a list of attributes with python. Sadly, I have multiple attributes with the same name thus I can't add them to the table. Also I don't want my program to stop because of that. Now I'm trying with this solution:

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)

I've pasted the long query code from this answer. The table is created with the first attribute as intended but as I would start to add more columns I get:

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

What am I missing?

I'd suggest simply building up the create table statement instead of building the table and then altering it to add columns to it!

You can get rid of duplicates in a list by using the following code:

listWithoutDups = list(dict.fromkeys(listWithDups))

Then, you can build your statement as follows:

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

You'll note I included double quotes around the column names -- that's necessary if you want to create columns that don't follow Oracle standards (include special characters, spaces, etc.) but be aware that also makes the names case sensitive and you will need to specify quotes as well when you perform any operation on the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM