android - SQLite 主键设置错误 - 为什么会这样?
问题描述
我正在尝试使用 DB Handler 制作数据库和表,并在 MainActivty 中插入数据。
问题是 Data instertig 功能仅在我没有设置主键时才起作用。
这是日志猫。
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);
}
解决方案
来自官方指南SQLiteConstraintException
指示违反完整性约束的异常。
你应该更正声明
String sql = "CREATE TABLE " + TABLE_INFO + "( _id INTEGER PRIMARY KEY
和
if (cursor.getInt(0) == idCombine){
然后卸载并再次运行。
推荐阅读
- swift - ARSceneView 中使用哪个图像作为参考?
- r - 在函数中设置时,数据帧行/列的重新排序不起作用
- loops - 在 SAS 程序上循环整个代码多次导致错误
- javascript - 将带有换行符和空格的输入拆分为数字数组会给出数组末尾有额外的 0
- c# - Equals() 方法在比较时无法识别相似/相同的字符
- cygwin - 我需要一种方法来更改 Msys2 配置以使用 Arch Linux AUR 服务器镜像而不是 Msys2 镜像
- android - 库中的伴侣对象在应用程序中不可用
- javascript - 如何禁用之前为预订选择的日期?
- angular - Angular 材质 - 弹性布局和卡片
- node.js - 您如何(如果可能)使用以下代码在网站中实现 Bcrypt 和 JWT?