postgresql 将查询结果导出到文件

方法1:进入查询终端,输入o  aa.out

查询结果将输出到当前目录的aa.out 文件

方法2: 将查询语句写a.sql中,

alias sql2="export PGPASSWORD=xxxxx; psql -h 192.168.1.107 -p 5439 -U dev -d 'data数据库名'"

sql2 -c a.sql > a.out

第二种缺点,除了结果外,将所有的屏幕内容输出到文件

psql  -d 'xxx'   -c "select name, gender, birthday, mobile_phone  from patients where mobile_phone != ''  and birthday > '1975-01-01' and  birthday <  '1994-01-01'; "  >  useful.txt

 

恢复备份文件到数据库

psql -h localhost -U hao -d dbname < aa.bak

备份到文件

pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql

 

CREATE USER ha WITH PASSWORD '123';
CREATE DATABASE prometheus OWNER USER;

GRANT ALL PRIVILEGES ON DATABASE prometheus to ha;
ALTER ROLE hao CREATEDB;

psql -h localhost -U ha -d dbname < aa.bak

mongo-query

db.cam.find( { "packageName":{"$in":["starz","id"]}}).limit(1).pretty()

附:mac postgresql安装及初始化

这里使用homebrew安装

brew install postgresql

等待安装完成后,初始化:

initdb /usr/local/var/postgres

启动服务:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

设置开机启动

ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

创建数据库和账户

mac安装postgresql后不会创建用户名数据库,执行命令:

createdb

然后登录PostgreSQL控制台:

psql

使用l命令列出所有的数据库,看到已存在用户同名数据库、postgres数据库,但是postgres数据库的所有者是当前用户,没有postgres用户。按:q退出查看

之后需要做以下几件事:

  1. 创建postgres用户

     CREATE USER postgres WITH PASSWORD 'password';
    
  2. 删除默认生成的postgres数据库

     DROP DATABASE postgres;
    
  3. 创建属于postgres用户的postgres数据库

     CREATE DATABASE postgres OWNER postgres;
    
  4. 将数据库所有权限赋予postgres用户

     GRANT ALL PRIVILEGES ON DATABASE postgres to postgres;
    
  5. 给postgres用户添加创建数据库的属性

     ALTER ROLE postgres CREATEDB;
    

这样就可以使用postgres作为数据库的登录用户了,并可以使用该用户管理数据库

登录控制台指令

psql -U [user] -d [database] -h [host] -p [post]

-U指定用户,-d指定数据库,-h指定服务器,-p指定端口

上方直接使用psql登录控制台,实际上使用的是缺省数据

user:当前mac用户
database:用户同名数据库
主机:localhost
端口号:5432,postgresql的默认端口是5432

完整的登录命令,比如使用postgres用户登录

psql -U postgres -d postgres

常用控制台命令

password:设置当前登录用户的密码
h:查看SQL命令的解释,比如h select。
?:查看psql命令列表。
l:列出所有数据库。
c [database_name]:连接其他数据库。
d:列出当前数据库的所有表格。
d [table_name]:列出某一张表格的结构。
du:列出所有用户。
e:打开文本编辑器。
conninfo:列出当前数据库和连接的信息。
password [user]: 修改用户密码
q:退出
 
作者:聪明叉
链接:https://www.jianshu.com/p/10ced5145d39
來源:简书