Program Tip

psql에서 데이터베이스를 전환하는 방법은 무엇입니까?

programtip 2020. 9. 27. 13:49
반응형

psql에서 데이터베이스를 전환하는 방법은 무엇입니까?


MySQL에서는 use database_name;

psql에 해당하는 것은 무엇입니까?


PostgreSQL에서는 \connect클라이언트 도구 psql 메타 명령을 사용할 수 있습니다 .

\connect DBNAME

또는 간단히 :

\c DBNAME

당신과 함께 데이터베이스에 연결할 수 있습니다 \c <database>또는 \connect <database>.


PSQL 프롬프트에서 다음을 수행 할 수 있습니다.

\connect (or \c) dbname

다음을 사용하여 연결할 수 있습니다.

\c dbname

psql로 연결할 때 데이터베이스를 선택할 수 있습니다. 이것은 스크립트에서 사용할 때 편리합니다.

sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test

psql의 메타 명령 사용 \c or \connect [ dbname [ username ] [ host ] [ port ] ] | conninfo( documentation 참조 ).

예: \c MyDatabase

참고 것을 \c\connect메타 명령은 대소 문자를 구분합니다 .


\l특정 데이터베이스에 저장된 프로 시저 \c위해 데이터베이스 DatabaseName이 db로 전환하는 경우\df


아래 문을 사용하여 postgreSQL RDMS 내부에있는 다른 데이터베이스로 전환합니다.

\c databaseName

시작시 특정 데이터베이스로 전환하려면 다음을 시도하십시오.

/Applications/Postgres.app/Contents/Versions/9.5/bin/psql vigneshdb;

기본적으로 Postgres는 포트 5432에서 실행됩니다. 다른 포트에서 실행되는 경우 명령 줄에서 포트를 전달해야합니다.

/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p2345 vigneshdb;

간단한 별칭으로 편리하게 만들 수 있습니다.

.bashrc또는 에서 별칭 만들기.bash_profile

function psql()
{
    db=vigneshdb
    if [ "$1" != ""]; then
            db=$1
    fi
    /Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p5432 $1
}

psql명령 줄에서 실행 하면 기본 데이터베이스로 전환됩니다. psql anotherdb, 시작시 인수에 이름이있는 db로 전환됩니다.


질문에 명시 적으로 언급되지는 않았지만 목적은 특정 스키마 / 데이터베이스에 연결하는 것입니다.

또 다른 옵션은 스키마에 직접 연결하는 것입니다. 예:

sudo -u postgres psql -d my_database_name

출처 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.

다음을 사용하여 연결할 수 있습니다.

\ c dbname

POSTGRESQL 또는 SQL에 대해 가능한 모든 명령을 보려면 다음 단계를 따르십시오.

  1. rails dbconsole (현재 ENV 데이터베이스로 재 인증됩니다)

  2. \? (POSTGRESQL 명령의 경우)

또는

  1. \ h (SQL 명령의 경우)

  2. Press Q to Exit


You can also connect to a database with a different ROLE as follows.

\connect DBNAME ROLENAME;

or

\c DBNAME ROLENAME;

As mentioned in the other answers, you need to change connection to use a different database.

Postgres works with schemas. You can have multiple schemes in a single database. So, if you're working within the same database, and want to change schema, You can do:

SET SCHEMA 'schema_name';

참고URL : https://stackoverflow.com/questions/3949876/how-to-switch-databases-in-psql

반응형