【发布时间】:2020-04-03 14:02:36
【问题描述】:
我正在尝试使用 DB Handler 制作数据库和表格,并在 MainActivty 中插入数据。
问题是数据插入功能只有在我没有设置主键时才起作用。
这是原木猫。
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: keikoTable._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
DBhandler.class
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_INFO + "(_id text PRIMARY KEY , year text, " +
" month text, date text, chek integer, log text)";
db.execSQL(sql);
}
MainActivity.java
public void dbInsert (String year, String month, String date, String log) {
int doublechk = 0;
String idCombine = year + month + date + doublechk;
Cursor cursor = readdb.rawQuery("SELECT _id FROM " + TABLE_INFO, null);
while (cursor.moveToNext()){
if (cursor.getString(0) == idCombine){
doublechk ++;
idCombine = year + month + date + doublechk;
} else {
break;
}
}
String sql = "INSERT INTO " + TABLE_INFO + " VALUES ('" + idCombine + "', '" + year + "', '"+ month + "', '"
+ date + "', '" + doublechk + "', '" + log + "')";
db.execSQL(sql);
}
【问题讨论】: