【问题标题】:Not allow to insert data into database if the data is already availabe in table如果数据已在表中可用,则不允许将数据插入数据库
【发布时间】:2014-01-22 07:20:57
【问题描述】:

我有三个表(培训、人员和出勤)。表之间的连接是;培训具有与人相同的领域。而出勤表只有training_id和person_id两个字段。当人员注册到培训时,training_id 和 person_id 插入到出勤表中。好的,我可以插入新人。当已经参加培训的人想要更新自己时,表(人)会更新,但在出勤表中,会再次插入人。我想要的是当这个人更新自己时,考勤表不应该再次插入他。

我试过了;

public void registerToTraining(int training_id) {
    DatabaseHelper db = DatabaseHelper.getInstance();
    String query = "SELECT * FROM attendance WHERE training_id = "
            + Integer.toString(training_id) + " AND person_id = "
            + Integer.toString(this.getId()) + ";";

    db.sqlCommand(query);

    if(The query does not return one row or more){

        String command = "INSERT INTO attendance (training_id , person_id) VALUES ("
                + Integer.toString(training_id)
                + ", "
                + Integer.toString(this.getId()) + ") ;";

        db.sqlCommand(command);
    }

【问题讨论】:

标签: android android-sqlite insert-update


【解决方案1】:

首先查询然后数据库然后使光标移动到第一个或不移动。

if(cursor.moveFirst)
{
Aleady exsist data.
}else
{
 new data insert
}

【讨论】:

  • 老兄,我不想在这里使用光标。我想用上面的方法。你能检查一下编辑过的部分并帮助我解决这个问题吗?
  • 是的,通过这种方式,您可以检查数据是否已经在数据库中。
  • 我只知道没有实现的想法。你能把它改成正确的方式吗?
  • 光标 cursor = database.rawQuery(query, null); if (!cursor.moveToFirst()) { String command = "插入出席 (training_id , person_id) 值 (" + Integer.toString(training_id) + ", " + Integer.toString(this.getId()) + ") ;"; db.sqlCommand(命令); }
  • 谢谢,如果可以,请投票并接受这个对其他人也有帮助的答案...
【解决方案2】:

您可以在创建表时对表的列使用 UNIQUE 约束,并在违反约束时跳过冲突行 (http://www.sqlite.org/lang_conflict.html)

CREATE TABLE attendance (training_id INT, person_id INT, UNIQUE(training_id, person_id) 
   ON CONFLICT IGNORE);

【讨论】:

  • 老兄!我想坚持我的代码。你的方式可以完成,但我不想改变我的方式。
猜你喜欢
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
相关资源
最近更新 更多