You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLite中通过Server ID获取对应行的本地ID?

解决SQLite中通过服务器ID获取本地ID并更新笔记的问题

你的核心需求是通过服务器返回的sid找到本地SQLite中对应笔记的本地ID,进而执行更新操作,以下是具体实现方案:

关键修改点

  1. 优化查询逻辑:仅查询需要的本地ID列,同时用参数化查询避免SQL注入风险;
  2. 提取本地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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:18:38