psql - 读取SQL文件并输出到CSV

时间:2016-08-19 20:04:46

标签: postgresql psql

我有一个SQL文件my_query.sql

select * from my_table

使用psql,我可以在这个sql文件中读到:

\i my_query.sql

或者将其作为arg传递:

psql -f my_query.sql

我可以将查询字符串的结果输出到csv:

\copy (select * from my_table) to 'output.csv' with csv header

有没有办法将这些结合起来,以便我可以将查询结果从SQL文件输出到CSV?

4 个答案:

答案 0 :(得分:3)

不幸的是,没有这样的烘焙功能,所以你需要一点点bash-fu才能让它正常工作。

raw.dat

CONN="psql -U my_user -d my_db" QUERY="$(sed 's/;//g;/^--/ d;s/--.*//g;' my_query.sql | tr '\n' ' ')" echo "\\copy ($QUERY) to 'out.csv' with CSV HEADER" | $CONN fun删除所有分号,注释行和行尾注释,sed将换行符转换为空格(如@abelisto评论中所述):

tr

变为:

-- my_query.sql
select *
from my_table
where timestamp < current_date -- only want today's records
limit 10;

然后传入有效的select * from my_table where timestamp < current_date limit 10 命令:

psql

这是一个脚本:

<强> \copy (select * from my_table where timestamp < current_date) to 'out.csv' with csv header

sql_to_csv.sh

#!/bin/bash # sql_to_csv.sh CONN="psql -U my_user -d my_db" QUERY="$(sed 's/;//g;/^--/ d;s/--.*//g;' $1 | tr '\n' ' ')" echo "$QUERY" echo "\\copy ($QUERY) to '$2' with csv header" | $CONN > /dev/null

答案 1 :(得分:1)

你可以使用bash脚本来完成它。

dump_query_to_csv.sh:

#!/bin/bash

# Takes an sql query file as an argument and dumps its results
# to a CSV file using psql \copy command.
#
# Usage:
#
#  dump_query_to_csv.sh <sql_query_file> [<csv_output_filesname>]

SQL_FILE=$1
[ -z $SQL_FILE ] && echo "Must supply query file" && exit
shift

OUT_FILE=$1
[ -z $OUT_FILE ] && OUT_FILE="output.csv" # default to "output.csv" if no argument is passed

TMP_TABLE=ttt_temp_table_xx # some table name that will not collide with existing tables

## Build a psql script to do the work
PSQL_SCRIPT=temp.psql

# create a temporary database table using the SQL from the query file
echo "DROP TABLE IF EXISTS $TMP_TABLE;CREATE TABLE $TMP_TABLE AS" > $PSQL_SCRIPT
cat $SQL_FILE >> $PSQL_SCRIPT
echo ";" >> $PSQL_SCRIPT

# copy the temporary table to the output CSV file
echo "\copy (select * from $TMP_TABLE) to '$OUT_FILE' with csv header" >> $PSQL_SCRIPT

# drop the temporary table
echo "DROP TABLE IF EXISTS $TMP_TABLE;" >> temp.sql

## Run psql script using psql
psql my_database < $PSQL_SCRIPT # replace my_database and add user login credentials as necessary

## Remove the psql script
rm $PSQL_SCRIPT

您需要编辑脚本中的psql行以连接到您的数据库。还可以增强脚本以将数据库和帐户凭据作为参数。

答案 2 :(得分:0)

可接受的解决方案是正确的,但是我使用Windows,必须使其通过批处理(命令)文件运行。如果有人需要,请在此处发布

@echo off

echo 'Reading file %1'
set CONN="C:\Program Files\PostgreSQL\11\bin\psql.exe" -U dbusername -d mydbname
"C:\Program Files\Git\usr\bin\sed.exe" 's/;//g;/^--/ d;s/--.*//g;' %1 | "C:\Program Files\Git\usr\bin\tr.exe" '\n' ' ' > c:\temp\query.txt
set /p QUERY=<c:\temp\query.txt
echo %QUERY%

echo \copy (%QUERY%) to '%2' WITH (FORMAT CSV, HEADER) | %CONN%

答案 3 :(得分:0)

我认为最简单的方法是利用shell的变量扩展能力:

psql -U my_user -d my_db -c "COPY ($(cat my_query.sql)) TO STDOUT WITH CSV HEADER" > my_query_results.csv
相关问题