Tester
Tester

Reputation: 4635

How to count number of columns in a table in SQLITE?

How can I count the number of columns in a table in a sqlite database in Android?

Upvotes: 5

Views: 17370

Answers (5)

user1461607
user1461607

Reputation: 2760

You can use SELECT count() FROM PRAGMA_TABLE_INFO('your_table');

Reference: https://www.sqlite.org/pragma.html#pragfunc

Upvotes: 2

Kennet
Kennet

Reputation: 5796

A query returns a Cursor which has methods like getColumnCount().

Upvotes: 9

user841021
user841021

Reputation: 25

Here you go!

-(NSInteger)dbFieldCount:(NSString *)dbname
{
    NSString *query = [NSString stringWithFormat:@"PRAGMA table_info(%@)",dbname];
    const char *query2 = [query UTF8String];
    NSInteger nFields =0;
    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, query2, -1, &compiledStatement, NULL) == SQLITE_OK) 
    {
         while(sqlite3_step(compiledStatement) == SQLITE_ROW)
         {
               nFields++;
         }
    }
    sqlite3_finalize(compiledStatement);
    return nFields;
}

Upvotes: 0

user609239
user609239

Reputation: 3366

Here is the code and it runs perfectly without any error.

public Cursor getAllTitles(){
   return db.query(DATABASE_TABLE, new String[] {
        KEY_ROWID,KEY_ISBN,KEY_TITLE,KEY_PUBLISHER},
        null,null,null,null,null);
}

Now create the following object in onCreate() method to call above getAllTitles() method.

Cursor c = db.getAllTitles();
c.getColumnCount(); //this line will give the number of columns in table.

Upvotes: 2

dhaag23
dhaag23

Reputation: 6126

You can use pragma table_info(foo_table) and count the number of rows returned

Upvotes: 8

Related Questions