问题
I have a table in my db called 'mytable'. I'd like to clear it so that I can continue to collect and analyze 'fresh data' from it.
Something like
conn = psycopg2.connect(database = mydb_name, host = mydb_server, user = mydb_uname, password = mydb_pwd)
cur = conn.cursor()
cur.execute("DROP TABLE mytable;")
Isn't going to work for me, because as far as I understand it, this destroys the table. I don't want to destroy/re-create... Just to flush all data.
How can I work this out?
回答1:
Truncate tablename
Is useful for this, table stays just dropping the data!
If you have foreign keys you need to use the following
Truncate tablename CASCADE
For many tables do like this
Truncate table1, table2, table3
Your example
Cur.execute("truncate mytable;")
回答2:
This sql query should delete all records from a table...
DELETE FROM mytable; // not DELETE * FROM mytable;
来源:https://stackoverflow.com/questions/15712239/psql-how-to-flush-database-content-without-dropping-table