【问题标题】:Check if couple of values exists in SQLite database检查 SQLite 数据库中是否存在几个值
【发布时间】:2019-06-29 23:42:35
【问题描述】:

我的 SQLite 数据库中有一个表,它由一对 int 组成,我想在添加新行之前检查一对是否已经存在。

我有这个函数从表 TableName(id1, id2) 中返回数据:

public Cursor getIds() {
        return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }

在其他课程中,我有这些:

int int1 = 14
int int2 = 2564

if (????) {
        m.addToTable(int1, int2);
} else {
        //Datas already exists
}

我需要做什么才能将 int1 与 id1 列中的值和 int2 与 id2 列中的值进行比较?

【问题讨论】:

    标签: java android database sqlite


    【解决方案1】:

    创建这个方法:

    public boolean existIds(int id1, int id2) {
        Cursor c = db.rawQuery(
                "SELECT * FROM " + TABLE_NAME + " WHERE id1 = ? AND id2 = ?",
                new String[]{String.valueOf(id1), String.valueOf(id2)}
        );
        boolean result = c.getCount() > 0;
        c.close();
        return result;
    }
    

    现在你可以在你的代码中使用它了:

    int int1 = 14
    int int2 = 2564
    
    if (!existIds(int1, int2)) {
        m.addToTable(int1, int2);
    } else {
        //do something because the ids already exist
    }
    

    【讨论】:

    • 谢谢,这正是我需要的!
    • 这可能适合 OP 的用例,但通常请注意,这种方法不是线程安全的。
    【解决方案2】:

    如果您计划最终在您的 SQLite 表中进行插入操作,并且您想防止这种情况发生,如果有一条记录已经包含这两个值,那么请考虑以下选项:

    INSERT INTO TableName (id1, id2)
    SELECT ?, ?
    WHERE NOT EXISTS (SELECT 1 FROM TableName WHERE id1 = ? and id2 = ?);
    

    到? 占位符,您将绑定要插入的两个值。对于您提供的示例,您最终将运行此查询:

    INSERT INTO TableName (id1, id2)
    SELECT 14, 2564
    WHERE NOT EXISTS (SELECT 1 FROM TableName WHERE id1 = 14 and id2 = 2564);
    

    【讨论】:

    • 感谢您的帮助,但@forpas 的回答更适合我的程序
    • @VanDiest 请记住,您接受的答案不是线程安全的。如果检查通过,仍然有可能另一个线程进来做同样的插入,从而导致重复记录。
    • 考虑使用明确编号(或命名)的参数,这样您只需绑定每个值一次而不是两次:select ?1, ?2 from ... where id1 = ?1 and id2 = ?2 ...
    猜你喜欢
    • 2014-04-03
    • 2017-10-21
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多