Deleting all the records from a table
Often, you'll need to empty a table of all of its records so you can reload the
data. You can do this with a delete statement with just the table as an argument. For example, in the video, Jason deleted the table extra_employees by executing as follows:
delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)
Do be careful, though, as deleting cannot be undone!
Diese Übung ist Teil des Kurses
Introduction to Databases in Python
Anleitung zur Übung
- Import
deleteandselectfrom sqlalchemy. - Build a
deletestatement to remove all the data from thecensustable. Save it asdelete_stmt. - Execute
delete_stmtvia theconnectionand save theresults. - Submit the answer to
selectall remaining rows from thecensustable and print the result to confirm that the table is now empty!
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# Import delete, select
from sqlalchemy import ____, ____
# Build a statement to empty the census table: stmt
delete_stmt = ____
# Execute the statement: results
results = ____
# Print affected rowcount
print(results.rowcount)
# Build a statement to select all records from the census table : select_stmt
select_stmt = select([census])
# Print the results of executing the statement to verify there are no rows
print(connection.execute(select_stmt).fetchall())