为什么我在getColumnIndex方法中获得-1

时间:2013-02-28 06:26:38

标签: android database sqlite android-cursor

 private static final String DATABASE_CREATE = "CREATE TABLE "
          + DATABASE_TABLE_USERS + "(" + KEY_ROW_ID + 
         " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME
          + " TEXT NOT NULL," + KEY_PASSWORD + " TEXT NOT NULL," + KEY_LOGIN_ATTEMPTS + " INTEGER NOT NULL," + KEY_ZIP + " TEXT," +
          KEY_STREET + " TEXT," + KEY_EMAIL + " TEXT NOT NULL," + KEY_PHONE + " TEXT);";

我在on_create方法中创建数据库:        db.execSQL(DATABASE_CREATE);

我有这个方法:

 public int getLoginAttempts(String u_name) {

    String [] columns = new String [] {DB_Helper.KEY_NAME};
    Cursor c = database.query(DB_Helper.DATABASE_TABLE_USERS, columns, DB_Helper.KEY_NAME + "= ?",
             new String[] {u_name},
             null,
             null,
             null);

    if(!c.moveToFirst()) return -1;

    int c_index = c.getColumnIndex(DB_Helper.KEY_LOGIN_ATTEMPTS);

    int num = c.getInt(c_index);
    c.close();
    return num;
}

c_index总是等于-1。这意味着该列不存在。但确实如此。并且应该只返回一条记录(因为u_names是唯一的)。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

这是因为在查询中您只选择名称列

替换此行

String [] columns = new String [] {DB_Helper.KEY_NAME};

String [] columns = new String [] {DB_Helper.KEY_NAME, DB_Helper.KEY_LOGIN_ATTEMPTS};