AIR and sqLite : if table exists conditional
Asked Answered
W

3

3

How do I get a Boolean value in AS3 whether a table or an entry exists in the database?

Wisla answered 5/1, 2011 at 7:23 Comment(0)
B
10

As opposed to finding it manually with SQL you should use the built in Schema information classes/functions. Here is an example of how it would work.

public function doesTableExist(connection:SQLConnection, tableName:String):Boolean
{
    connection.loadSchema();
    var schema:SQLSchemaResult = connection.getSchemaResult();

    for each (var table:SQLTableSchema in schema.tables)
    {
        if (table.name.toLowerCase() == tableName.toLowerCase())
        {
            return true;
        }
    }
    return false;
}
Bonn answered 2/6, 2011 at 16:13 Comment(2)
This is the best way. AS3 SQLite does not support PRAGMA. Official DocumentationDarrendarrey
This does indeed work best. A few heeds of warning: 1.) I would suggest wrapping this whole function in a try-catch statement, because if you have NO tables at all in your database, an error will get thrown stating there is no schema to load, and of course cause issues during runtime. 2.) If you are using an async database connection you MUST make sure it has fully loaded before you start checking the schema, or else you will get an error complaining about the connection being bad.Leatherette
D
2

There is no simple statement to achieve boolean value, but you can:

  1. use PRAGMA table_info(tbl_status) and analize list.

  2. try to execute SELECT col FROM table_name in try...catch block, in case of error simply set variable to bool.

BTW, maybe you need to use IF NOT EXISTS in create statement for table, index creation...

Doublecross answered 5/1, 2011 at 8:30 Comment(2)
Thanks, I'll give that a try. I do already have CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS, but was wondering how to get this in as3Wisla
didn't get around to test it yet as I switched to a DataObject, but will give it a try when I get a chance, thanks.Wisla
C
1

can be useful for someone - for async connection:

connection.loadSchema();
connection.addEventListener(SQLEvent.SCHEMA, check_result);

private function check_result(event:SQLEvent):void{
var schema:SQLSchemaResult = connection.getSchemaResult();
//as above
}
Congratulatory answered 19/6, 2014 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.