KelvinS
KelvinS

Reputation: 3071

How to properly update a table in the user computer?

I have a conceptual doubt related to updating fields in a database.

I have developed a Qt (C++) application that uses SQLite to store data. The SQLite file (.db) is stored in the user computer. The file is automatically created when the user opens the application for the first time.

The problem is that I need to update one table in that database. I can do it using the ALTER TABLE command, but how can I properly update the table in the database that is allocated in the user computer?

Do I need to create a function that checks if the table doesn't have the fields that I want and then runs the ALTER TABLE command or there is some other easy/correct way to to this?

Upvotes: 1

Views: 138

Answers (1)

cbuchart
cbuchart

Reputation: 11555

A more general solution may be to use a version number entry in the DB and centralise changes based on this. If you don't have it, you can create it with this update. At least I think it becomes clearer in the code and you have a single point for future modifications:

void update_database_to_current_version() {
  const int version = current_db_version(); // returns 1 if version is not found

  if (version < 2) { // since version 2 table XYZ has new structure, match here
      // 'ALTER TABLE' ...
  }

  // if (version < N) // DB changes starting in version N
  // ...

  update_db_version_to_newest();
}

On the other hand, as far as I now, you can run the ALTER TABLE several times without affecting the table, so that may be a quicker option if you prefer.

Upvotes: 3

Related Questions