Checking if a column exists in an application database in Android
My function based on @martinpelants answer:
private boolean existsColumnInTable(SQLiteDatabase inDatabase, String inTable, String columnToCheck) {
Cursor mCursor = null;
try {
// Query 1 row
mCursor = inDatabase.rawQuery("SELECT * FROM " + inTable + " LIMIT 0", null);
// getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1
if (mCursor.getColumnIndex(columnToCheck) != -1)
return true;
else
return false;
} catch (Exception Exp) {
// Something went wrong. Missing the database? The table?
Log.d("... - existsColumnInTable", "When checking whether a column exists in the table, an error occurred: " + Exp.getMessage());
return false;
} finally {
if (mCursor != null) mCursor.close();
}
}
Simply call:
boolean bla = existsColumnInTable(myDB,"MyTable","myColumn2check");
cursor.getColumnIndex(String columnName)
returns -1 if, the column doesn't exist. So I would basically perform a simple query like "SELECT * FROM xxx LIMIT 0,1" and use the cursor to determine if the column, you are looking for, exists
OR
you can try to query the column "SELECT theCol FROM xxx" and catch an exception