-1

As a newbie I wonder what the right way to do this is: I've watched several tutorials all create a database but then use CREATE TABLE x IF NOT EXISTS in a way that will only run on the user's device.

I tried to find out if that's the "right" way to do it - and why we apparently avoid just creating and deploying a nicely set up database complete with all expected tables - but have found nothing relevant so far (probably because I still lack the vocabulary to better search for it...).

It would seem to me that this might introduce unnecessary errors on the user's device and I can't see any advantages!

Looking forward to your insights!


EDIT:

I've been pointed towards Room for database handling, which I will look into! But my question is still unanswered. Rephrased:
When/Where are db tables created (beforehand/during build/on user's device)? And what's the reasoning behind the decision?

Rautermann
  • 334
  • 3
  • 10
  • 2
    the fact that you're seeing people manually write Sqlite statements _probably_ (not definitely) means that the tutorials might be a bit outdated. with Room that isn't really a concern or a problem anymore. either way, there isn't really a correct answer to your question, if it was an absolute requirement then it would be enforced and would not be optional – a_local_nobody Jul 30 '20 at 18:04
  • Yes, could've been outdated ones - or they just tried to get students fimiliar with SQLite. I will look into _Room_! – Rautermann Jul 31 '20 at 08:08
  • speaking as someone who has done both room and Sqlite, in my opinion there's really no point in teaching anyone Sqlite, sure, it'll teach you to appreciate Room more, but it's so different compared to how room works there isn't any real point in knowing it, it's a complete different implementation, but this is entirely my opinion and conversational – a_local_nobody Jul 31 '20 at 08:34
  • Yes, for Android, Room is probably all you need nowadays, but SQLite is used in other domains, too - so I'm glad I know the basics! – Rautermann Jul 31 '20 at 09:16

1 Answers1

1

With Android sqlite the canonical way is to use SQLiteOpenHelper to manage database schema lifecycle. The helper onCreate() that should create the tables in the first place gets invoked when the database is first opened at runtime with e.g. getWritableDatabase(). See When is SQLiteOpenHelper onCreate() / onUpgrade() run? for more details.

I consider IF NOT EXISTS a code smell. For example, with SQLiteOpenHelper onCreate() is invoked at most once per database file, so in a correct program there could not possibly be any pre-existing table to begin with. Therefore IF NOT EXISTS would be just hiding other problems only to be discovered much later.

laalto
  • 150,114
  • 66
  • 286
  • 303