Getting the type of a column in SQLite

Calling:

PRAGMA table_info(table1);

will dump the table information, e.g.

cid|name                 |type    |notnull |dflt_value |pk
0  |id_fields_starring   |INTEGER |0       |           |1
1  |fields_descriptor_id |INTEGER |1       |           |0
2  |starring_id          |INTEGER |1       |           |0
3  |form_mandatory       |INTEGER |1       |1          |0
4  |form_visible         |INTEGER |1       |1          |0

and simply find the row in the cursor with notnull=1 and dflt_value=1


Edit:

To list all columns defined as INTEGER NOT NULL DEFAULT 1 this would work (helper is your instance of SQLiteOpenHelper):

SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("PRAGMA table_info(table1)", null);
try {
    int nameIdx = cursor.getColumnIndexOrThrow("name");
    int typeIdx = cursor.getColumnIndexOrThrow("type");
    int notNullIdx = cursor.getColumnIndexOrThrow("notnull");
    int dfltValueIdx = cursor.getColumnIndexOrThrow("dflt_value");
    ArrayList<String> integerDefault1NotNull = new ArrayList<String>();
    while (cursor.moveToNext()) {
        String type = cursor.getString(typeIdx);
        if ("INTEGER".equals(type)) {
            // Integer column
            if (cursor.getInt(notNullIdx) == 1) {
                // NOT NULL
                String defaultValue = cursor.getString(dfltValueIdx);
                if ("1".equals(defaultValue)) {
                    integerDefault1NotNull.add(cursor.getString(nameIdx));
                }
            }
        }
    }
    System.out.println("integerDefault1NotNull now contains a list of all columns " +
            " defined as INTEGER NOT NULL DEFAULT 1, " + integerDefault1NotNull);
} finally {
    cursor.close();
}

Leave a Comment