如何使用psql连接postgresql版本12的数据库?

bfnvny8b  于 2023-02-22  发布在  PostgreSQL
关注(0)|答案(4)|浏览(275)

我想连接到我在psql中新建的名为"test"的数据库,我看到过这样的命令:

Connection
  \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                         connect to new database (currently "postgres")

那是什么意思?
我试着写:

\c {test|- postgres|- localhost|- 5432|- | conninfo}

但出现错误:

invalid integer value "5432|-" for connection option "port"

我该怎么办?

qoefvg9y

qoefvg9y1#

你有没有试
\c postgresql://user@localhost/test
或者
\c "host=localhost port=5432 dbname=test connect_timeout=10"
Source

rks48beu

rks48beu2#

当您已经连接到一个数据库并希望连接到另一个数据库时,使用\c。
例如,如果您连接了postgres数据库,并希望连接测试数据库,则可以执行is \c测试
并且如果使用PSQL则

./psql -U postgres -d test -p 5432
bxpogfeg

bxpogfeg3#

而我只是发现,这种方式将工作,为所有其他人喜欢我:

\l

这样你就会看到你创建的数据库列表,如果你想看到某个表,那么

\c db_name

然后,如果数据库存在,您将成功连接它。

kg7wmglp

kg7wmglp4#

我的PostgreSQL版本是- psql(15. 2(Ubuntu15.2-1.pgdg22.04+1))
Connect(\c)用于psql命令提示符,命令语法为-

\connect (or \c) [ dbname [ username ] [ host ] [ port ] ]

如果我们不传递任何值,此命令将从先前的连接中获取所有四个输入值的值。我们可以理解如下-

postgres=# \c (if we don't pass anything on this prompt then it will take all values (db name, user name, host and port) from previous connection.)
 postgres=# \c test (here we are passing one value and this value be taken as database name, for other values user name, host name and port will be used from previous connection) 
 postgres=# \c test testuser (here host and port will be inherit from previous connection while first value will be taken as database name while second value will be taken as user name)
 postgres=# \c test testuser localhost (here port will be used from previous connection while other three values db name, user name and host will be taken from given three values)
 postgres=# \c test testuser localhost 5432 (in this command all four values are passed hence it will pick from here only)

执行上述命令后,输出为-

postgres=# \c testdb testadmin localhost 5432
    Password for user testadmin: 
    You are now connected to database "testdb" as user "testadmin".

相关问题