首页 > 解决方案 > SQLite 主键设置错误 - 为什么会这样?

问题描述

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

问题是 Data instertig 功能仅在我没有设置主键时才起作用。

这是日志猫。

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);
}

标签: androiddatabasesqlite

解决方案


来自官方指南SQLiteConstraintException

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

你应该更正声明

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

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

然后卸载并再次运行


推荐阅读