SQLALCHEMY delete all rows in existing database in python

Question:

I have created a sqlite database in python according to a tutorial:

from sqlalchemy import create_engine
engine = create_engine('sqlite:///DB.db') 

And next time I run the python script, it has old data in there.

How can I delete all rows, reinitialise or even delete the database (where is it located?)?

Asked By: nolimits

||

Answers:

If you don’t need the data to persist, you can use an in-memory sqlite database, using

engine = create_engine('sqlite://') 

If you still want the data to be accessible after you run your script, but each execution should just start anew, simply delete the DB.db file wherever the working directory is, at the start of your script:

import os
if os.path.exists('DB.db'):
   os.remove('DB.db')
Answered By: MarcinJ

You can use the following code:

file_location = engine.url.database
# To stop using the file
engine.dispose()

# Drop file
os.remove(file_location)
Answered By: Machkour Oke
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.