I have implemented simple cache stored in SQLite database. For one client there is one table in database. I want to automaticaly create this table if it not exists. What will be better sollution, checking if table exists using query: SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'; or using CREATE TABLE IF NOT EXISTS table_name (...)? I have to do this every time I need cache, so I wonder which way will be more efficient and more correct.
I’m using PDO, so maybe there is some cleverer way to do this?
Solution:
Use PDO::errorCode to find if table doesn’t exists.
I’d go with
create table if not existsbecause it’ll be compatible with other databases should you need it one day (in case of sqlite particularly it’s unlikely you’ll switch, but still).Also if you check
sqlite_masterand don’t find your table there you need to send another query to create it. Withcreate tableyou’re only sending one query, although with table structure defined in it, but if your table structure is not hard to generate or is predefined, you’ll have no problems supplying it every time withcreate table.It also depends on how likely is it for your tables not to exist. If that is not very likely and you just want your app to be safe and self-maintaining you can just assume they exist and process exceptions to create table when queries assuming they exist fail.