如何在SQLite中通过Server ID获取对应行的本地ID?
解决SQLite中通过服务器ID获取本地ID并更新笔记的问题
你的核心需求是通过服务器返回的sid找到本地SQLite中对应笔记的本地ID,进而执行更新操作,以下是具体实现方案:
关键修改点
- 优化查询逻辑:仅查询需要的本地ID列,同时用参数化查询避免SQL注入风险;
- 提取本地ID:确认sid存在后,从Cursor中读取对应行的本地ID值。
修改后的代码
public void loadServerNotes(String title, String des, String sid){ SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = null; // 仅查询本地ID列,使用参数化查询避免SQL注入 String queryLocalId = "SELECT " + COLUMN_ID + " FROM " + TABLE_NAME + " WHERE " + COLUMN_SID + " = ?;"; cursor = db.rawQuery(queryLocalId, new String[]{sid}); boolean exists = (cursor.getCount() > 0); if (exists){ // 移动Cursor到结果行并获取本地ID if (cursor.moveToFirst()) { int localId = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)); updateNote(localId, title, des, Api.NAME_SYNCED_WITH_SERVER, sid); } } else { createNote(title, des, Api.NAME_SYNCED_WITH_SERVER, sid); } // 确保Cursor关闭,避免资源泄漏 if (cursor != null) { cursor.close(); } }
额外说明
- 参数化查询:用
?占位符替代直接拼接sid字符串,既防止SQL注入,也适配sid为字符串类型的场景; - getColumnIndexOrThrow:列名拼写错误时会抛出异常,便于排查问题,也可改用
getColumnIndex(找不到返回-1),但需额外判断有效性; - 资源安全:推荐使用try-with-resources语法自动关闭Cursor,进一步避免资源泄漏:
try (Cursor cursor = db.rawQuery(queryLocalId, new String[]{sid})) { boolean exists = (cursor.getCount() > 0); if (exists){ if (cursor.moveToFirst()) { int localId = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)); updateNote(localId, title, des, Api.NAME_SYNCED_WITH_SERVER, sid); } } else { createNote(title, des, Api.NAME_SYNCED_WITH_SERVER, sid); } }
你的SQLite列对应中文含义:
- COLUMN_ID:本地ID列
- COLUMN_TITLE:标题列
- COLUMN_DES:描述列
- COLUMN_STATUS:状态列
- COLUMN_SID:服务器ID列
内容的提问来源于stack exchange,提问作者Homie
相关产品推荐
相关产品推荐

