2 Replies Latest reply on Nov 28, 2010 5:06 PM by Jens Wegar

    Detect whether table exists

    Spiders-Design.co.uk

      Upon opening I need my application to check to see if a table exists in the database and if not run setup. How would I do this (No flex please)

        • 1. Re: Detect whether table exists
          commadelimited Level 2

          Is this for a "First Run" type of behavior?

           

          I don't think there's a "check to see if table exists" type of behaviour, but you could write simple query to get the count of all records in the table, then listen for the SQLError event. Something like this could work.

           

          dbQuery = new air.SQLStatement();

          dbQuery.sqlConnection = db;

          dbQuery.text = "SELECT COUNT(id) as cnt FROM yourTable";

          selectStmt.addEventListener(air.SQLErrorEvent.ERROR, function(event){

               // error throw, database does not exist

               air.Introspector.Console.log(event);

          });

          dbQuery.execute();

          • 2. Re: Detect whether table exists
            Jens Wegar Level 1

            Assuming you're using AIR SQLite. In your create table statement you can simply say that it should only be created if it doesn't exist:

             

            CREATE TABLE IF NOT EXISTS my_table (id,val1, val2...)

             

            and run the create statement every time you start the app (or whenever access to that table is needed for the first time during runtime). The table will be created the first time the statement is run, but after that it will simply be ignored if the table already exists.

             

            If you need to do other things in your setup than create tables, then perhaps consider storing a flag in a file in applicationStorageDirectory and checking for that when your app starts. This doc might help for that:

             

            http://help.adobe.com/en_US/air/build/WS5b3ccc516d4fbf351e63e3d118666ade46-7ff2.html