DBAtlas · 数据库运维图谱

导出数据(CSV / 到文件)

Oracle

-- CSV with SQL*Plus (spool)
SET MARKUP CSV ON
SPOOL customer.csv
SELECT id, name, email FROM customer;
SPOOL OFF

-- Logical export with Data Pump (from the shell)
expdp app_user/password tables=customer directory=dir_dmp dumpfile=customer.dmp

CSV 使用 SQL*Plus SET MARKUP CSV ON + SPOOL(12.2+)。迁移 schema/表时,Data Pump(expdp)生成二进制 .dmp,再用 impdp 导入另一个 Oracle 数据库。

PostgreSQL

-- Server side
COPY (SELECT id, name, email FROM customer) TO '/data/customer.csv' WITH (FORMAT csv, HEADER true);

-- Client side (psql)
\copy (SELECT id, name, email FROM customer) TO 'customer.csv' WITH (FORMAT csv, HEADER true)

COPY ... TO 将查询结果写入文件(服务器端,需要权限);psql \copy 写入客户端文件。HEADER true 会添加表头行。

MySQL

-- To a file on the server
SELECT id, name, email FROM customer
INTO OUTFILE '/data/customer.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

-- To the client: mysql -e ... > file (tab-separated)
-- mysql -e "SELECT * FROM customer" shop > customer.tsv

SELECT ... INTO OUTFILE 在服务器上创建文件(需要 secure_file_priv 路径和 FILE 权限;不能覆盖已有文件)。客户端输出请用 mysql -e 重定向。

SQL Server

-- Export with bcp (from the shell)
bcp "SELECT id, name, email FROM shop.dbo.customer" queryout customer.csv -c -t, -S server -T

-- or the whole table
bcp shop.dbo.customer out customer.dat -n -S server -T

bcp out/queryout 将数据写入文件:-c 字符模式,-t, 字段分隔符,-n 原生二进制格式。查询结果使用 queryout。SSMS 中的“结果保存到文件”也是一种选择。

MongoDB

# Export CSV (fields must be specified)
mongoexport --db=shop --collection=customer --type=csv --fields=id,name,email --out=customer.csv

# As JSON
mongoexport --db=shop --collection=customer --out=customer.json

mongoexport 生成 CSV/JSON;CSV 必须通过 --fields 显式指定列。使用 --query 过滤。完整的二进制备份推荐使用 mongodump。

Redis

# Scan keys (SCAN instead of KEYS in production)
redis-cli --scan --pattern 'customer:*' > keys.txt

# For a full data backup, download an RDB snapshot to the client side (non-blocking)
redis-cli --rdb ./dump.rdb

没有内置的结构化 CSV 导出。键列表使用 --scan(非阻塞),完整数据使用 RDB 文件:redis-cli --rdb 会把服务器在后台生成的快照下载到本地文件;如果希望文件留在服务器上,使用 BGSAVE。SAVE 会阻塞主线程,生产环境勿用。若还需要值,循环读取 scan 结果。

Elasticsearch

# Export with elasticdump
elasticdump --input=http://localhost:9200/customer --output=customer.json --type=data

# For large data, paged reads with scroll / point-in-time
GET customer/_search?scroll=1m
{ "size": 1000, "query": { "match_all": {} } }

没有直接的 CSV 导出。获取全部数据可使用 elasticdump,或通过 scroll/PIT(point-in-time)分页读取 _search。转换为 CSV 需要 Logstash csv output 或外部工具。

在 DBAtlas 中打开 →