首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Cursor 查詢報 ColumnIndex -1 錯誤:列名不存在或拼寫錯誤

     編輯:程式設計綜合問答

開發者查詢 SQLite 時,title 正常讀取,但 bj 列報 getColumnIndex("bj") 返回 -1,隨後讀取拋出 IllegalStateException: Couldn't read row 0, col -1。

錯誤代碼

Cursor cursor = myDatabase.rawQuery("select ids,title,times from goodtime", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    // ...
    String beijing = cursor.getString(cursor.getColumnIndex("bj")); // 這裡炸
}

建表語句

CREATE TABLE goodtime(
    ids INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    content TEXT,
    times TEXT,
    ptpath TEXT,
    mppath TEXT,
    vdpath TEXT,
    islock INTEGER,
    password TEXT,
    bj TEXT   -- 這裡有 bj 列
);

根本原因:SELECT 子句未包含 bj 列

rawQuery("select ids,title,times from goodtime") 只查了 3 列,Cursor 根本不包含 bj 列,所以 getColumnIndex("bj") 返回 -1。

修復方案

方案一:SELECT 列出所有需要的列(推薦)

Cursor cursor = myDatabase.rawQuery(
    "SELECT ids, title, times, bj FROM goodtime", null);

方案二:查所有列(簡單但效率稍低)

Cursor cursor = myDatabase.rawQuery("SELECT * FROM goodtime", null);

避坑檢查清單

  1. SELECT 列表 是否包含後續要讀取的所有列名
  2. 列名拼寫:SQLite 不區分大小寫,但建議與建表語句完全一致
  3. Cursor 為空:先判斷 cursor != null && cursor.getCount() > 0 再 moveToFirst()
  4. 列索引緩存:循環外獲取索引,避免重複調用 getColumnIndex
    int idxId = cursor.getColumnIndex("ids");
    int idxTitle = cursor.getColumnIndex("title");
    int idxBj = cursor.getColumnIndex("bj");
    while (cursor.moveToNext()) {
        int id = cursor.getInt(idxId);
        String title = cursor.getString(idxTitle);
        String bj = cursor.getString(idxBj);
    }
    

調試技巧

// 打印 Cursor 所有列名
String[] columnNames = cursor.getColumnNames();
Log.d("CursorColumns", Arrays.toString(columnNames));
// 輸出:[ids, title, times] ← 確認缺 bj

一句話總結:想讀什麼列,SELECT 就得寫什麼列。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved