PostgreSQL.connect_database

PostgreSQL.connect_database(database_name=None, verbose=False)[source]

Establish a connection to a database.

Parameters:
  • database_name (str | None) – name of a database; when database_name=None (default), the database name is input manually

  • verbose (bool | int) – whether to print relevant information in console as the function runs, defaults to False

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.

>>> testdb.connect_database(verbose=True)
Being connected with postgres:***@localhost:5432/testdb.

>>> testdb.connect_database(database_name='postgres', verbose=True)
Connecting postgres:***@localhost:5432/postgres ... Successfully.
>>> testdb.database_name
'postgres'

>>> testdb.connect_database(database_name='testdb', verbose=True)
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.database_name
'testdb'

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