In MySQL, I used use database_name;
What's the psql
equivalent?
In PostgreSQL, you can use the \connect
meta-command of the client tool psql:
\connect DBNAME
or in short:
\c DBNAME
Using psql's meta-command \c or \connect [ dbname [ username ] [ host ] [ port ] ] | conninfo
(see documentation).
Example: \c MyDatabase
Note that the \c
and \connect
meta-commands are case-sensitive.
Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.
Another option is to directly connect to the schema. Example:
sudo -u postgres psql -d my_database_name
Source from man psql
:
-d dbname
--dbname=dbname
Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
documentation for more information.
If you want to switch to a specific database on startup, try
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql vigneshdb;
By default, Postgres runs on the port 5432. If it runs on another, make sure to pass the port in the command line.
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p2345 vigneshdb;
By a simple alias, we can make it handy.
Create an alias in your .bashrc
or .bash_profile
function psql()
{
db=vigneshdb
if [ "$1" != ""]; then
db=$1
fi
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p5432 $1
}
Run psql
in command line, it will switch to default database; psql anotherdb
, it will switch to the db with the name in argument, on startup.
Listing and Switching Databases in PostgreSQL When you need to change between databases, you’ll use the \connect command, or \c followed by the database name as shown below:
postgres=# \connect database_name
postgres=# \c database_name
Check the database you are currently connected to.
SELECT current_database();
postgres=# \l
postgres=# \list
psql
, the front-end for PostgreSQL? – Peter Mortensenset schema 'schema_name';
orset search_path to schema_name;
– a_horse_with_no_name