如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
如何从命令行删除PostgreSQL中的所有表?
我不想删除数据库本身,只想删除其中的所有表和所有数据。
当前回答
对于macOS。如果您有一个通过PostgreSQL应用程序的终端,一个简单的命令可以帮助您:
drop table "organisations" cascade;
其他回答
如果要删除的所有内容都属于同一用户,则可以使用:
drop owned by the_user;
这将删除用户拥有的所有内容。
这包括用户拥有(=创建)的物化视图、视图、序列、触发器、模式、函数、类型、聚合、运算符、域等(实际上是:所有)。
您必须用实际的用户名替换_user,目前没有选项删除“当前用户”的所有内容。即将推出的9.5版本将拥有current_user拥有的选项drop。
手册中的更多详细信息:http://www.postgresql.org/docs/current/static/sql-drop-owned.html
对于macOS。如果您有一个通过PostgreSQL应用程序的终端,一个简单的命令可以帮助您:
drop table "organisations" cascade;
drop schema public cascade;
应该会成功。
在Windows批处理文件中:
@echo off
FOR /f "tokens=2 delims=|" %%G IN ('psql --host localhost --username postgres --command="\dt" YOUR_TABLE_NAME') DO (
psql --host localhost --username postgres --command="DROP table if exists %%G cascade" sfkb
echo table %%G dropped
)
以防万一。。。清理Postgresql数据库的简单Python脚本
import psycopg2
import sys
# Drop all tables from a given database
try:
conn = psycopg2.connect("dbname='akcja_miasto' user='postgres' password='postgres'")
conn.set_isolation_level(0)
except:
print "Unable to connect to the database."
cur = conn.cursor()
try:
cur.execute("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_schema,table_name")
rows = cur.fetchall()
for row in rows:
print "dropping table: ", row[1]
cur.execute("drop table " + row[1] + " cascade")
cur.close()
conn.close()
except:
print "Error: ", sys.exc_info()[1]
确保复制后缩进正确,因为Python依赖它。