【问题标题】:SQLite primay key setting error - why so?SQLite 主键设置错误 - 为什么会这样?
【发布时间】:2020-04-03 14:02:36
【问题描述】:

我正在尝试使用 DB Handler 制作数据库和表格,并在 MainActivty 中插入数据。

问题是数据插入功能只有在我没有设置主键时才起作用。

这是原木猫。

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: keikoTable._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)

DBhandler.class

 @Override
public void onCreate(SQLiteDatabase db) {

    String sql = "CREATE TABLE " +  TABLE_INFO + "(_id text PRIMARY KEY , year text, " +
            " month text, date text, chek integer, log text)";

    db.execSQL(sql);
}

MainActivity.java

 public void dbInsert (String year, String month, String date, String log) {
    int doublechk = 0;


     String idCombine = year + month + date + doublechk;

     Cursor cursor = readdb.rawQuery("SELECT _id FROM " + TABLE_INFO, null);

     while (cursor.moveToNext()){
         if (cursor.getString(0) == idCombine){
             doublechk ++;
             idCombine = year + month + date + doublechk;
         } else {
             break;
         }
     }


    String sql = "INSERT INTO " + TABLE_INFO  + " VALUES ('" + idCombine + "', '" + year + "', '"+ month  + "', '"
            + date  + "', '" + doublechk + "', '" + log + "')";
    db.execSQL(sql);
}

【问题讨论】:

    标签: android database sqlite


    【解决方案1】:

    来自官方指南SQLiteConstraintException

    表示违反完整性约束的异常。

    你应该纠正陈述

    String sql = "CREATE TABLE " +  TABLE_INFO + "( _id INTEGER PRIMARY KEY 
    

    if (cursor.getInt(0) == idCombine){
    

    然后卸载并再次运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2017-01-01
      • 2021-04-14
      • 1970-01-01
      • 2018-10-15
      相关资源
      最近更新 更多