PostgreSQL.create_table

PostgreSQL.create_table(table_name, column_specs, schema_name=None, verbose=False)[source]

Create a table.

Parameters:
  • table_name (str) – Name of the table to be created.

  • column_specs (str) – Specifications for each column of the table.

  • schema_name (str | None) – Name of the schema; if schema_name=None (default), it defaults to DEFAULT_SCHEMA (i.e. 'public').

  • verbose (bool | int) – Whether to print relevant information to the console; defaults to False.

Examples:

>>> from pyhelpers.dbms import PostgreSQL
>>> testdb = PostgreSQL(database_name='testdb', verbose=True)
Password (postgres@localhost:5432): ***
Creating a database: "testdb" ... Done.
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> # Create a new table named 'test_table'
>>> tbl_name = 'test_table'
>>> col_spec = 'col_name_1 INT, col_name_2 TEXT'
>>> testdb.create_table(table_name=tbl_name, column_specs=col_spec, verbose=True)
Creating a table "public"."test_table" ... Done.
>>> testdb.table_exists(table_name=tbl_name)
True
>>> # Get information about all columns of the table "public"."test_table"
>>> test_tbl_col_info = testdb.get_column_info(table_name=tbl_name, as_dict=False)
>>> test_tbl_col_info.head()
                            column_0      column_1
table_catalog                 testdb        testdb
table_schema                  public        public
table_name                test_table    test_table
column_name               col_name_1    col_name_2
ordinal_position                   1             2
>>> # Get data types of all columns of the table "public"."test_table"
>>> test_tbl_dtypes = testdb.get_column_dtype(table_name=tbl_name)
>>> test_tbl_dtypes
{'col_name_1': 'integer', 'col_name_2': 'text'}
>>> testdb.validate_column_names(table_name=tbl_name)
'"col_name_1", "col_name_2"'
>>> # Drop the table "public"."test_table"
>>> testdb.drop_table(table_name=tbl_name, verbose=True)
To drop the table "public"."test_table" from postgres:***@localhost:5432/testdb
? [No]|Yes: yes
Dropping "public"."test_table" ... Done.
>>> # Delete the database "testdb"
>>> testdb.drop_database(verbose=True)
To drop the database "testdb" from postgres:***@localhost:5432
? [No]|Yes: yes
Dropping "testdb" ... Done.