微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – UNIQUE约束失败:sqlite数据库:android

我想在表中插入值.但是只插入了一个值.当我尝试插入新值时,我在log cat中收到错误.

日志猫显示

abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint Failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase: android.database.sqlite.sqliteConstraintException: UNIQUE constraint Failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteConnection.executeForLastInsertedRowId(sqliteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteSession.executeForLastInsertedRowId(sqliteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteStatement.executeInsert(sqliteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteDatabase.insertWithOnConflict(sqliteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at android.database.sqlite.sqliteDatabase.insert(sqliteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at com.example.siddhi.tiMetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.tiMetablelayout E/sqliteDatabase:     at com.example.siddhi.tiMetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)

它在插入行时显示这两行的错误.

db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));

EventTableHelper

public class EventTableHelper extends sqliteOpenHelper {


    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";



    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(sqliteDatabase db) {
        //createTable(db);
    }

    public void createTable(sqliteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execsql(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execsql("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        sqliteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        sqliteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.movetoFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }



    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        sqliteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.movetoFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.movetoNext());
        }

        // return contact list
        return conList;
    }
}

怎么解决这个?

解决方法:

您的代码可能违反了KEY_ID字段上的主键唯一性约束.

两种可能的解决方案是

>确保EventData.getId()返回每个对象的唯一值.现在,我没有看到你将任何标识符传递给它的构造函数,也许所有事件都插入了相同的id值.
>如果您不关心自己生成ID,可以将AUTOINCREMENT设置添加到KEY_ID列定义中.这样,KEY_ID字段将自动填充,每行将具有自己的唯一值.在那里,不要忘记删除自己添加KEY_ID到ContentValues.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐