PostgreSQL.table_exists

PostgreSQL.table_exists(table_name, schema_name=None)

Check whether a table exists.

Parameters
  • table_name (str) – name of a table

  • schema_name (str) – name of a schema; when schema_name=None (default), it defaults to DEFAULT_SCHEMA (i.e. 'public')

Returns

whether the table exists in the currently-connected database

Return type

bool

Examples:

>>> from pyhelpers.dbms import PostgreSQL

>>> testdb = PostgreSQL('localhost', 5432, 'postgres', database_name='testdb')
Password (postgres@localhost:5432): ***
Creating a database: "testdb" ... Done.
Connecting postgres:***@localhost:5432/testdb ... Successfully.

>>> tbl_name = 'points'

>>> testdb.table_exists(table_name=tbl_name)  # (if 'public.points' does not exist)
False

>>> testdb.create_table(table_name=tbl_name, column_specs='column_0 INT', verbose=1)
Creating a table: "public"."points" ... Done.
>>> testdb.table_exists(table_name=tbl_name)
True

>>> testdb.drop_table(table_name=tbl_name, verbose=True)
To drop the table "public"."points" from postgres:***@localhost:5432/testdb
? [No]|Yes: yes
Dropping "public"."points" ... Done.

>>> testdb.drop_database(verbose=True)  # Delete the database "testdb"
To drop the database "testdb" from postgres:***@localhost:5432
? [No]|Yes: yes
Dropping "testdb" ... Done.