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

Android SQLite 插入崩潰:SQL 字串拼接錯誤導致語法異常

     編輯:程式設計疑難解答

崩潰現場

// 錯誤代碼
private void insertData(SQLiteDatabase db, String word, String detail) {
    db.execSQL("insert into dict values(null,?,?)" + new String[]{word, detail});
}

錯誤:"sql" + String[] 會呼叫陣列 toString() 產生 "[Ljava.lang.String;@hashcode",非合法 SQL。

正確寫法:參數化查詢

// 修正版
private void insertData(SQLiteDatabase db, String word, String detail) {
    db.execSQL("insert into dict (word, detail) values(?,?)", 
               new String[]{word, detail});
}

補充修正:建表欄位名一致性

建表 SQL:create table dict(_id integer primary key autoincrement, word text, detail text);

插入時指定欄位 (word, detail),_id 自動遞增,避免 null 佔位報錯。

其他潛在問題檢查清單

  • 查詢 SQL 欄位名拼寫:detail vs details(原代碼不一致)。
  • Cursor 索引:getString(1) 對應 word,getString(2) 對應 detail,正確。
  • Bundle 傳值:putSerializable 需確保 Map 實作 Serializable(HashMap 已實作)。

崩潰堆疊 Logcat 錯誤詳情

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