约束失败-SQLite 3-Android

问题描述

| 我的SQLite上有下表。
    StringBuilder createSql = new StringBuilder();
    createSql.append(\"create table LIBRARY ( \");
    createSql.append(\"id integer primary key,\");
    createSql.append(\"title text,\");
    createSql.append(\"author text,\");
    createSql.append(\"publisher text,\");
    createSql.append(\"thumbnailUrl text,\");
    createSql.append(\"formatType text,\");
    createSql.append(\"contentUrl text,\");
    createSql.append(\"publicationType text,\");
    createSql.append(\"favorite text,\");
    createSql.append(\"started text,\");
    createSql.append(\"normalizedTitle text,\");
    createSql.append(\"downloaded integer,\");
    createSql.append(\"wasDownloaded text \");
    createSql.append(\");\");
下面的代码在该表上插入一个值。
public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put(\"title\",item.getTitle());
    row.put(\"author\",item.getAuthor());
    row.put(\"publisher\",item.getPublisher());
    row.put(\"thumbnailUrl\",item.getThumbnail());
    row.put(\"formatType\",item.getFormat());
    row.put(\"contentUrl\",item.getContentUrl());
    row.put(\"publicationType\",item.getPublicationType());
    row.put(\"favorite\",item.isFavorite() ? \"YES\" : \"NO\");
    row.put(\"id\",item.getItemId());
    row.put(\"normalizedTitle\",StringUtil.normalize(item.getTitle()));
    row.put(\"downloaded\",Calendar.getInstance().getTimeInMillis());
    row.put(\"wasdownloaded\",item.hasContent() ? \"YES\" : \"NO\");

    long id = db.insert(\"LIBRARY\",null,row);
    add(id,item.getCategories());
}
但是执行它时,出现以下错误。
Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
怎么了?     

解决方法

您的主键不会自动递增。然后您要插入第一行,它有一个键,然后您插入另一行,它有相同的键,但是主键不能相同! 然后,您要插入具有指定键的项目,我认为该错误意味着该键已存在的项目。     ,将您的createSQL构建器更改为...
createSql.append(\"id integer primary key autoincrement,\");
也。插入时,您无需设置id字段。相反,您应该做的是在函数顶部进行检查。
if(item.getItemID() == 0)
{
    //Run update here instead.
    //Set the id on the ContentValues here
}
else
{
    //Run insert statement instead.
    //Don\'t set the id in the ContentValues here.
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...