Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a column exists in an application database in Android

Is there a nice way in Android to see if a column exists in a table in the application database? (I know there are questions similar to this one already, but there don't seem to be any that are Android specific.)

like image 441
Lunchbox Avatar asked Jan 18 '11 01:01

Lunchbox


2 Answers

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

like image 175
martinpelant Avatar answered Oct 01 '22 02:10

martinpelant


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"); 
like image 24
flexo Avatar answered Oct 01 '22 03:10

flexo