约束失败 - SQLite的3 - 安卓

问题描述:

我对我的SQLite下表。约束失败 - SQLite的3 - 安卓

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 

怎么了?

你的主键是不会自动递增。然后,您插入第一行是得到了一个键,然后你插入另一个是得到了相同的一个,但主键不能是一样的!

然后你将与指定键的项目,我认为错误的意思项与此键已经存在。

+0

HMM ..现在我明白我的问题了,谢谢。 – 2011-04-12 18:16:10

更改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. 
} 
+0

是啊,这是我的问题,我打电话了两次。我需要第二个更新。但我不需要自动增量键。 – 2011-04-12 18:49:19