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
來源:簡書
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM