When working with a database with multiple databases, you will often find yourself switching between them to execute specific operations.
This tutorial explores the various methods that we can use to switch between PostgreSQL databases.
Method 1: Using the PSQL Utility
The PSQL command provides a command-line interface to connect and interact with a PostgreSQL database. For example, when working in the terminal using the “psql” command, we can switch a database using the “\c” command.
Start by connecting to the server using the “psql” command as follows:
Replace the username, hostname, and port to your desired parameters.
Once connected, you can switch the database using the “\c” command as shown in the following:
Replace the database_name with the database name to which you wish to connect.
For example, to switch to the Pagila database, you can run the following command:
This should change the database and print a success message as follows:
Once you switch, your prompt should change to reflect the currently selected database.
Method 2: Using the SET Command
Another method that we can use to switch the databases is the SET command in the PSQL utility.
Run the following command in the psql prompt:
Similarly, replace the database_name with your target database.
For example:
This switches you to the target database which allows you to run the commands in the specified database.
Method 3: Connection Clients
In some cases, you could be using a different PostgreSQL client other than the default psql utility. In such a case, you can specify your target database in the connection settings.
It is good to note that this method differs depending on your connection client and the implementation of your programming language.
For example, if we use a custom client in Python, we can use the database parameter in the connection string to define the target database.
The example code is as follows:
connection = psycopg2.connect(
host="localhost",
port="5432",
database="pagila",
user="postgres",
password="password"
)
…
connection.close()
In the given example code, we use the connection parameter to define the connection details to the server including the target database.
NOTE: The previous code uses the psycopg2 package. Ensure that you have the required dependencies installed.
Conclusion
We explored the three fundamental methods that you can use to switch the databases in the PostgreSQL server. Whether using the psql utility or a custom client, switching the databases is a common task, and you will often find yourself doing so.