2011-04-12 7 views
0

SQLite에 다음 표가 있습니다.제약 조건 실패 - SQLite 3 - Android

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 

무엇이 잘못 되었습니까?

답변

3

기본 키가 자동으로 증가하지 않습니다. 그런 다음 키가있는 첫 번째 행을 삽입 한 다음 동일한 키가있는 다른 행을 삽입하지만 기본 키는 같을 수 없습니다!

그런 다음 지정된 키가있는 항목을 삽입하려고합니다. 오류는이 키가있는 항목이 이미 있음을 의미한다고 생각합니다.

+0

HMM .. 이제 내 문제를 이해합니다. –

1
또한

createSql.append("id integer primary key autoincrement, "); 

... 당신의 createSQL 빌더로 변경

. 삽입 할 때 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

그래, 내 문제 야, 나는 그것을 두 번이나 부른다. 두 번째에 대한 업데이트가 필요합니다. 하지만 자동 증가 키가 필요하지 않습니다. –