初學者在這裏再次需要建議。嘗試按照教程向/從數據庫添加/編輯/刪除數據。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();
}
}
我試過刪除:TABLE_ROW_ID +「整數主鍵自動增量非空,」+但它似乎沒有作出改變,並存在相同的錯誤。我將如何使用表中已存在的ID插入記錄? (我已經嘗試了各種各樣) – d347hkn3ll 2011-05-20 16:21:26
如果表中已經存在該記錄,則更新它不會插入它。插入用於創建新條目。 – Eric 2011-05-20 16:35:07
該表中尚未存在該記錄。數據庫已經存在(在此應用程序啓動時會創建此文件之前創建的類文件) – d347hkn3ll 2011-05-20 17:33:49