5

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

5 Answers 5

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can LIMIT the query to 1 to reduce access time
8

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

Comments

2

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.

1 Comment

Can you please elaborate the parameters of the db.query()? Thanks.
2

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

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

Comments

0

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;
}

2 Comments

This code could not work in java, android and uses objective-c as prog language.
sqlite3_data_count or sqlite3_column_count is good alternative to looping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.