我在表....中插入了一个数据我想看到整个表的行,列和数据。我如何通过命令显示它?


当前回答

如果您的数据库是密码保护,那么解决方案将是:

PGPASSWORD=password  psql -U username -d dbname -c "select * from my_table"

其他回答

I have no doubt on @Grant answer. But I face few issues sometimes such as if the column name is similar to any reserved keyword of postgresql such as natural in this case similar SQL is difficult to run from the command line as "\natural\" will be needed in Query field. So my approach is to write the SQL in separate file and run the SQL file from command line. This has another advantage too. If you have to change the query for a large script you do not need to touch the script file or command. Only change the SQL file like this

psql -h localhost -d database -U postgres -p 5432 -a -q -f /path/to/the/file.sql

打开命令提示符,进入Postgres安装的目录。在我的情况下,我的Postgres路径是“D:\TOOLS\Postgresql-9.4.1-3”。然后移动到Postgres的bin目录。因此命令提示符显示为"D:\TOOLS\Postgresql-9.4.1-3\bin>" 现在我的目标是从用户表中使用“UserId”值选择“UserName”。数据库查询是"Select u "UserName" from users u其中u."UserId"=1"。

对于postgres的psql命令提示符,同样的查询如下所示。

D:\TOOLS\Postgresql-9.4.1-3\bin>psql - u postgress - D DatabaseName -h localhost - t -c "Select u.\"UserName\" from users u其中u.\"UserId\"=1;

在有密码保护的数据库中直接执行SQL命令。它宁愿在命令行中使用连接字符串格式。 使用该命令:

psql -d postgresql://postgres:password@localhost:5432/dbname 
-c "create database sample1 --or any command"

## Using SQL file
PGPASSWORD=myPassword psql -h myDbHost -U myUser -p 5432 -d my_db -a -q -f /path/to/sql/file.sql
## Or
PGPASSWORD=myPassword psql -h myDbHost -U myUser -p 5432 -d my_db < /path/to/sql/file.sql

## Using command
PGPASSWORD=myPassword psql -h myDbHost -U myUser -p 5432 -d my_db -c "select * from my table limit 1;"

我还注意到查询

SELECT * FROM tablename;

在PSQL命令提示符上给出错误 而且

SELECT * FROM "tablename";

运行正常,很奇怪,所以别忘了双引号。 我一直喜欢数据库:-(