I need to check to see if a column exists and if it doesn\'t exist add it. From my research it looks like sqlite doesn\'t support IF statements and case statement should be
To get column names for a table:
PRAGMA table_info (tableName);
To get indexed columns:
PRAGMA index_info (indexName);
// This method will check if column exists in your table
public boolean isFieldExist(String tableName, String fieldName)
{
boolean isExist = false;
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
res.moveToFirst();
do {
String currentColumn = res.getString(1);
if (currentColumn.equals(fieldName)) {
isExist = true;
}
} while (res.moveToNext());
return isExist;
}
I have applied this solution:
public boolean isFieldExist(SQLiteDatabase db, String tableName, String fieldName)
{
boolean isExist = false;
Cursor res = null;
try {
res = db.rawQuery("Select * from "+ tableName +" limit 1", null);
int colIndex = res.getColumnIndex(fieldName);
if (colIndex!=-1){
isExist = true;
}
} catch (Exception e) {
} finally {
try { if (res !=null){ res.close(); } } catch (Exception e1) {}
}
return isExist;
}
It is a variant of code by Pankaj Jangid.
You cannot use ALTER TABLE with
case.
You are looking for getting the column names for a table::-
PRAGMA table_info(table-name);
Check this tutorial on PRAGMA
This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.
You did not specify a language, so assuming it's not pure sql, you can check for errors on column querying:
SELECT col FROM table;
if you get an error so you know the column is not there (assuming you know the table exists, anyway you have the "IF NOT EXISTS" for this), otherwise the column exists and then you can alter the table accordingly.
Similar to IF
in SQLite, CASE
in SQLite is an expression. You can't use ALTER TABLE
with it. See: http://www.sqlite.org/lang_expr.html