18

我正在寻找一种简单的方法来删除数据库中的所有数据并保留结构(表、关系等......)。我使用postgreSQL,但我认为,如果有一个命令可以做到这一点,它并不特定于postgres。

谢谢,

达米安

4

5 回答 5

31

使用 .dump 模式转储pg_dump。删除数据库,重新创建它并加载架构。

将您的数据库模式(-s 标签)转储到文件中:

pg_dump -s -f db.dump DB-NAME

删除数据库:

dropdb DB-NAME

重新创建它:

createdb DB-NAME

仅恢复架构:

pg_restore db.dump > psql DB-NAME

这应该适用于 PostgreSQL;其他 DBMS 可能有自己的工具。我不知道有任何通用工具可以做到这一点。

编辑:

在注释之后,您可能希望跳过该dropdb命令,而只需使用转储模式创建另一个数据库。如果一切顺利,您可以删除旧数据库:

pg_dump -s -f db.dump DB-NAME
createdb DB-NEW-NAME
pg_restore db.dump > psql DB-NEW-NAME

此时,您在 DB-NAME 处拥有完整的数据库,在 DB-NEW-NAME 处拥有一个空架构。确定一切正常后,使用dropdb DB-NAME.

于 2010-01-22T14:11:03.190 回答
6

You can do something like this:

export PGUSER=your_pg_user
export PGHOST=database.host
export PGPORT=port
export PGDATABASE=your_database

psql -qAtX -c "select 'TRUNCATE table ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' CASCADE;' from information_schema.tables where table_type = 'BASE TABLE' and not table_schema ~ '^(information_schema|pg_.*)$'" | psql -qAtX

It will do what's necessary.

Of course these exports are not necessary, but they will make it simpler to run 2 copies of psql without having to givem them all standard -U, -d, and so on, switches.

One thing though - using TRUNCATE to do so, while faster than DELETE, has it's drowbacks - for example - it is not being replicated by Slony and any other replication system that works on triggers. Unless you are working on PostgreSQL 8.4, and your replication knows how to use triggers on TRUNCATE.

于 2010-01-22T14:28:06.240 回答
2

我不是 Postgres 人,但一种选择是遍历表并对每个表发出Truncate命令。但是,您必须考虑可表关系 - 例如,您将无法在引用它的数据之前删除引用数据。

于 2010-01-22T14:10:23.853 回答
1

在 pgAdmin 中,您可以执行以下操作:

  • 右键单击数据库 -> 备份,选择“仅架构”
  • 删除数据库
  • 创建一个新数据库并像以前一样命名它
  • 右键新建数据库->还原->选择备份,选择“Schema only”
于 2017-03-29T12:06:56.357 回答
-1

您可以通过以下三个步骤在不受外键限制的情况下删除数据库的所有记录

  1. 获取数据库的脚本
    1. 右键单击您的数据库(您的数据库名称)
    2. 单击任务,然后单击“生成脚本”
    3. 指定位置
  2. 删除您的数据库库
  3. 重新创建具有相同名称的数据库并运行您生成的脚本

这样您就可以清空所有数据库

于 2016-05-14T12:04:21.740 回答