2011-05-20 104 views
2

初学者在这里再次需要建议。尝试按照教程向/从数据库添加/编辑/删除数据。SQLiteConstraintException:错误代码19:约束失败

但是尝试添加一个新的标题时,我收到以下错误:

ERROR/Database(278): Error inserting Book_Title=testtitle Book_Author=testauthor 

ERROR/Database(278): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 

我怀疑它的一个contraint上的ID,由于该数据库在前面的类文件已经创建。然而,我并不熟悉Java知道如何解决它。编辑和删除数据正常工作。

一些代码:

DatabaseManager.class:

public void addRow(String rowStringOne, String rowStringTwo) 
    { 
     // this is a key value pair holder used by android's SQLite functions 
     ContentValues values = new ContentValues(); 


     values.put(TABLE_ROW_ONE, rowStringOne); 
     values.put(TABLE_ROW_TWO, rowStringTwo); 


     // ask the database object to insert the new data 
     try{db.insert(TABLE_NAME, null, values);} 
     catch(Exception e) 
     { 
      Log.e("DB ERROR", e.toString()); 
      e.printStackTrace(); 
     } 
    } 



private class CustomSQLiteOpenHelper extends SQLiteOpenHelper 
    { 



     public CustomSQLiteOpenHelper(Context context) 
     { 
      super(context, DB_NAME, null, DB_VERSION); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) 
     { 
      // This string is used to create the database. It should 
      // be changed to suit your needs. 
      String newTableQueryString = "create table " + 
             TABLE_NAME + 
             " (" + 
             TABLE_ROW_ID + " integer primary key autoincrement not null," + 
             TABLE_ROW_ONE + " text," + 
             TABLE_ROW_TWO + " text" + 
             ");"; 




      // execute the query string to the database. 
      db.execSQL(newTableQueryString); 

     } 


     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
     { 
      // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION. 
      // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE. 
     } 
    } 
} 

AddData.class:

private void addRow() 
{ 
    try 
    { 
     // ask the database manager to add a row given the two strings 
     db.addRow 
     (

       textFieldOne.getText().toString(), 
       textFieldTwo.getText().toString() 

     ); 

     // request the table be updated 
     updateTable(); 

     // remove all user input from the Activity 
     emptyFormFields(); 
    } 
    catch (Exception e) 
    { 
     Log.e("Add Error", e.toString()); 
     e.printStackTrace(); 
    } 
} 

回答

0

你被告知要插入无法记录由于主键或外键/键的限制而插入。很可能你想插入已经在表中的ID的记录。
SQLIte AFAIK中没有autoincrement关键字,但在任何表中都有_ID属性,我建议您将它用作主键自动增量,而不是创建自己的。

发生异常会导致您不插入自定义主键,并且它不像您所想的那样是自动增量。

+0

我试过删除:TABLE_ROW_ID +“整数主键自动增量非空,”+但它似乎没有作出改变,并存在相同的错误。我将如何使用表中已存在的ID插入记录? (我已经尝试了各种各样) – d347hkn3ll 2011-05-20 16:21:26

+0

如果表中已经存在该记录,则更新它不会插入它。插入用于创建新条目。 – Eric 2011-05-20 16:35:07

+0

该表中尚未存在该记录。数据库已经存在(在此应用程序启动时会创建此文件之前创建的类文件) – d347hkn3ll 2011-05-20 17:33:49

0

尝试删除并重新创建数据库。

我看不出有什么错在你的代码,我怀疑在表定义,这使得数据库和代码不同步的变化

(我的代码以SQLite不以分号结束;,你可以试试这个)

相关问题