0

Python Version: 2.7 OS: Ubuntu 12.04

conn = sqlite3.connect("Database.db")
cursor = conn.cursor()
for id in ids:
    cursor.execute("DELETE FROM tablename WHERE id = ?", (id,))
    conn.commit()

Delete seems to work, but the size of "Database.db" remain the same. What could be the problem?

0

3 Answers 3

1

This isn't surprising. Databases are collections of files (or other units of storage). These files store data on something called a data page. Data pages contains rows. And tables are logical constructs with their rows stored on data pages.

When you delete a record from a table, you are changing the data pages that represent that table (perhaps even removing some). However, you are not changing the database, only the data in the table.

2
  • then what should I do to reduce the database size? Because the space is limited and I need to free up some space.
    – J.Joe
    Dec 4, 2016 at 16:34
  • @J.Joe . . . In SQLite, I believe you use vacuum: sqlite.org/lang_vacuum.html. Dec 4, 2016 at 18:45
1

Gordon has already explained why the database size does not change on disk. In the case of SQLite, you can use the VACUUM command to rebuild the database into minimal space after a large number of deletes.

The official docs are usually pretty dry when explaining these things. More info can be found here. Some snippets:

SQLite first copies data within a database file to a temporary database. This operation defragments the database objects, ignores the free spaces, and repacks individual pages. Then, SQLite copies the content of the temporary database file back to the original database file. The original database file is overwritten.

The VACUUM command does not change the content of the database except the rowid values. If you use INTEGER PRIMARY KEY column, the VACUUM does not change values of that column. However, if you use unaliased rowid, the VACUUM command will reset the rowid values. Besides changing the rowid values, the VACUUM command also builds the index from the scratch.

It is a good practice to perform the VACUUM command periodically, especially when you delete the large table or index.

It is important to note that the VACCUM command requires storage for hold the original file and also the copy.

-1

the size of "Database.db" maybe is not equal to the size of table.

Not the answer you're looking for? Browse other questions tagged or ask your own question.