Android - SQLite Cursor getColumnIndex() is case sensitive?

后端 未结 4 2020
孤街浪徒
孤街浪徒 2020-12-06 06:29

While working with SQLiteCursor in Android i came to know that the getColumnIndex() is behaving case sensitive for example:

Example:

4条回答
  •  情书的邮戳
    2020-12-06 06:55

    Another way would be to Query the database itself for the correct name by using PRAGMA table_info, So I wrote a method for just that:

    public class database {
        private SQLiteDatabase mainDB = null;
    
        private boolean CreateOrOpenDB() {
            try {
                if (mainDB == null || !mainDB.isOpen()) {
                    mainDB = Context.openOrCreateDatabase("mainDB", SQLiteDatabase.CREATE_IF_NECESSARY, null);
                }
            } catch (SQLiteException e) {
                return false;
            }
            return true;
        }
    
        private String GetTrueColumnName(String TableName, String column) {
            String TrueColName = "";
            if (CreateOrOpenDB()) {
                try {
                    Cursor c = mainDB.rawQuery("PRAGMA table_info(" + TableName + ");", null);
    
                    if (c != null) {
                        if (c.moveToFirst()) {
                            do {
                                String dbcolumn = c.getString(c.getColumnIndex("name"));
                                if (column.toLowerCase().equals(dbcolumn.toLowerCase())) {
                                    TrueColName = dbcolumn;
                                    break;
                                }
                            } while (c.moveToNext());
                        }
                        c.close();
                    }
                    mainDB.close();
                } catch (Exception e) {
                }
            }
            return TrueColName;
        }
    }
    

    then all you need to call is:

    String CorrectName = GetTrueColumnName(TableName, "RuLeS");

    and yes, I know it will be hard on the database. But it works and is stable

提交回复
热议问题