【问题标题】:sqlite database overwrites existing record than inserting new record in physical devicesqlite 数据库覆盖现有记录而不是在物理设备中插入新记录
【发布时间】:2018-10-28 12:22:00
【问题描述】:

我面临的挑战是我无法将新记录插入表中,而是覆盖了表中的第一条记录。

这发生在物理设备中,因为它在模拟器中运行良好。

以下是用于插入记录的代码:

Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss", Locale.getDefault());
            String strDate = formatter.format(date);

            //SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING);

            SQLiteDatabase db = this.getWritableDatabase();
            /*ContentValues values = new ContentValues();
            //values.put("UserId",1);
            values.put("NoQPassed", scoreValues.get("NoPassed"));
            values.put("NoQFailed", scoreValues.get("NoFailed"));
            values.put("NoQSkipped", scoreValues.get("NoSkipped"));
            values.put("SubjectName", scoreValues.get("strSubjectName"));
            values.put("CompletedDateTime", strDate);
            intRetVal= db.insert(score_Table_Name, null, values);*/

            String strQuery="insert into "+score_Table_Name+" values ('"+strDate+"','"+scoreValues.get("NoPassed")+
                    "','"+scoreValues.get("NoFailed")+"','"+scoreValues.get("NoSkipped")+"','"+scoreValues.get("strSubjectName")+"')";
            db.execSQL(strQuery);
            db.close();

尝试使用 db.insertdb.executeSQL 进行插入,但没有任何帮助。有人可以帮我解决我哪里出错了吗?

我没有添加任何主键或自动增量键来确保冲突不是因为该列。我们是否总是需要有主键才能插入新记录?

【问题讨论】:

  • 你怎么知道那一行超过写作?
  • 我正在从设备文件资源管理器中导出数据库文件,并检查数据库浏览器中用于 sqlite 的表内容是什么。我只找到最新插入的值。
  • 确保在任何地方插入后没有删除行。这里没有替换旧数据的逻辑。用于查看数据库github.com/amitshekhariitbhu/Android-Debug-Database

标签: android sqlite android-sqlite


【解决方案1】:

您可以使用下面的 getCount() 方法来计算出现次数。 if getCount(name)== 0 然后插入。否则不插入并尝试记录。

public int getCount(String name) {
    Cursor c = null;
    try {
        db = Dbhelper.getReadableDatabase();
        String query = "select count(*) from TableName where name = ?";
        c = db.rawQuery(query, new String[] {name});
        if (c.moveToFirst()) {
            return c.getInt(0);
        }
        return 0;
    }
    finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
}

但是如果你说你覆盖它,这个逻辑可能是无效的。我认为那个android sqlite没有覆盖的可能性。请检查在插入新记录之前,您可能会在任何地方删除数据库。看起来像是覆盖数据

【讨论】:

  • 你能告诉我你分享的代码背后的逻辑是什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多