E
E
EvaSpence2021-09-02 14:14:38
Python
EvaSpence, 2021-09-02 14:14:38

Python. How to check if a table exists in the database?

Can you please tell me how to fix the script?
It must check if such a table or column in a table exists in the database, and if not, then it will write the data, and if it does, it will say "Duplicate", but it will not crash out of the database

import psycopg2
    from psycopg2 import Error

    try:
        # Подключиться к существующей базе данных
        connection = psycopg2.connect(user="postgres",
                                    # пароль, который указали при установке PostgreSQL
                                    password="*****",
                                    host="127.0.0.1",
                                    port="5432",
                                    database="result_test_parsing")
            
        # Создайте курсор для выполнения операций с базой данных

        #  для проверки на дубль новой таблицы
        cursor = connection.cursor()
        checkTableExists = """SELECT table_name
                            FROM information_schema.tables
                            WHERE table_schema = 'databasename'
                            AND table_name = 'tablename';"""
        cursor.execute(checkTableExists)
        connection.commit()
        #  для создания новой таблицы
        create_table_query = '''CREATE TABLE value_result
                            (TESTID TEXT PRIMARY KEY     NOT NULL); '''

        # Выполнение команды: это создает новую таблицу
        cursor.execute(create_table_query)
        connection.commit()
        print("Таблица успешно создана в PostgreSQL")

        #SQL-запрос для вставки записей в таблицу базы данных
        cursor.execute(
    "INSERT INTO VALUE_RESULT (TESTID) VALUES ('fio-example')"
    )
        connection.commit()
        print('Запись успешно вставлена')
    except (Exception, Error) as error:
        print("Ошибка при работе с PostgreSQL", error)
    finally:
        if connection:
            cursor.close()
            connection.close()
            print("Соединение с PostgreSQL закрыто")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2021-09-02
@EvaSpence

If you just check for the existence of a table, then you can query

select * from pg_tables where tablename = 'value_result'

If you just need to swear when the table was not created or when the record failed, then you can use try .. except with catching a specific error code
try:
    cursor.execute(create_table_query)
except НужноеИсключение:
    print("таблица уже существует")

I don’t know what specific exceptions are used offhand, you can see the documentation:
https://www.psycopg.org/docs/errors.html
or derive it empirically
except Exception as e:
    print(e)

L
Larisa .•º, 2021-09-02
@barolina

CREATE TABLE IF NOT EXISTS value_result(   //add for PostgreSQL 9.1+

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question