SQLite:将数组字符串插入表中而不是增加ID

时间:2017-03-30 05:29:57

标签: java android sqlite android-studio

尝试将字符串数组插入表中,但插入的id不增加,第一个字符串已插入。我使用autoincreament作为id?

表格创建

//Multi Farm Table
String CREATE_MULTI_FARM_TABLE = "CREATE TABLE " + TABLE_MULTI_FARM + "(" +
        KEY_MULTI_FARM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_MULTI_FARM_FARM_NAME + " TEXT" + ")";
db.execSQL(CREATE_MULTI_FARM_TABLE);

插入记录功能

//Add Multi Farm
public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_MULTI_FARM_ID, multiFarm.getId());
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}

课程中的功能

public MultiFarmModel(String farmName){
    this.farmName = farmName;
}

插入代码

String smsContent = "InsertToTable A|B|C|D|E";
DBHandler db = new DBHandler(context);
                smsContent = smsContent.substring(smsContent.indexOf(" ")+1);
                String[] string = smsContent.split("\\|");
                db.deleteAllMultiFarmRecord();
                for (String s : string) {
                    Log.e("StringToInsert", s + " ? ");
                    db.addMultiFarm(new MultiFarmModel(s));
                }
            }

日志控制台

E/String Number: A|B|C|D|E
E/StringToInsert: A ? 
E/StringInsertId: 0
E/StringToInsert: B ? 
E/StringInsertId: -1
E/StringToInsert: C ? 
E/StringInsertId: -1
E/StringToInsert: D ? 
E/StringInsertId: -1
E/StringToInsert: E ? 
E/StringInsertId: -1

1 个答案:

答案 0 :(得分:1)

删除此KEY_MULTI_FARM_ID行,因为它是自动增量列...您传递相同的值,这就是它抛出错误的原因

public void addMultiFarm(MultiFarmModel multiFarm) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
   // values.put(KEY_MULTI_FARM_ID, multiFarm.getId()); 
    values.put(KEY_MULTI_FARM_FARM_NAME, multiFarm.getFarmName());
    //Insert Record
    Log.e("StringInsertId", "" + db.insert(TABLE_MULTI_FARM, null, values));
    db.close();
}