简体   繁体   中英

Can't insert data into Sqlite database

This is the code for me to insert data into the database. Everything is fine with no errors. I typed everything that I need supposedly.

But somehow I am still not able to insert the data. What is the reason? When I check the database, the table cart is empty.

public void insertrecord() {
    Bundle bundle = this.getIntent().getExtras();
    long rowId = bundle.getLong("rowId");

    mydb2 = dbhelper.getWritableDatabase();
    myCursor2 = mydb2.query(Dbhelper.CART_NAME, allColumns2, "ID_=" + String.valueOf(rowId), null, null, null, null);

    myCursor.moveToFirst();
    if (!myCursor.isAfterLast()) {
        String cartname = (myCursor.getString(myCursor.getColumnIndex(Dbhelper.COLUMN_TITLE)));
        mydb2.execSQL("insert into cart(id_, cartRecord) VALUES(" + rowId + ", '" + cartname + "');");
    }
}

What are you trying to do?
First you find the row with id_ = rowId and then if this row exists you want to insert another row with the same id_ ?
Isn't this id_ UNIQUE in the table?
Maybe you should do the opposite, meaning if this id_ does not exist then insert the new row with some value for cartname :

if (myCursor.getCount() == 0) {
    mydb2.execSQL("insert into cart(id_, cartRecord) VALUES(" + rowId + ", '" + cartname + "');");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM