简体   繁体   中英

SQLite stores value as -1 for one column, but other columns are fine

In my application recently I've added new column SUB_CATEGORY_ID to my existing table transactions . After I insert record with sub_category_id value as any integer, when I queried the table and checked it returns value as -1 for sub_category_id rest of the columns are fine. I checked value for sub_category_id before inserting it is not null and having integer values like 1,2,... But still it is saving the value as -1.

Any suggestions. Please find my code below.

Code to add Transaction:

public int addTransaction(int categoryId, int subCategoryId, int accountId, double amount,
                          String notes, String trxType, String subTrxType, int sourceTrxId) {

    Log.d("addTransaction", "before addTransaction "+subCategoryId);
    int flag=0;

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(CATEGORY_ID_COL, categoryId);
    contentValues.put(ACCOUNT_ID_COL, accountId);
    contentValues.put(AMOUNT_COL, amount);
    contentValues.put(DUE_DATE_COL, getDateTime());
    contentValues.put(CREATION_DATE, getDateTime());
    contentValues.put(NOTES_COL, notes);
    contentValues.put(TRANSACTION_TYPE_COL, trxType);
    contentValues.put(TRANSACTION_SUB_TYPE_COL, subTrxType);
    contentValues.put(SOURCE_TRX_ID_COL, sourceTrxId);
    contentValues.put(SUB_CATEGORY_ID_COL, subCategoryId);
    db.insert(TRANSACTIONS_TABLE_NAME, null, contentValues);
    flag=1;
    return flag;
}

Code to query transaction records returns -1 for sub_category_id column:

    String selectQuery1 = "SELECT TRX."+CATEGORY_ID_COL+", TRX."+SUB_CATEGORY_ID_COL+" from "+TRANSACTIONS_TABLE_NAME
            +" AS TRX ORDER BY DATETIME(TRX."+CREATION_DATE+") DESC LIMIT 50";
Cursor c1 = db.rawQuery(selectQuery1, null);
    if(c1.moveToFirst()){
        do{
            Log.d("fetchAllTrx", " CetgId="+c1.getLong(0)+" 
subcatgid="+c1.getLong(1));
        }while (c1.moveToNext());
    }
    c1.close();

A trap that many fall into at first, is assuming that the onCreate method runs every time and that changing the schema (adding/removing table or columns) can be implemented by just changing the SQL used to create the tables.

The onCreate method only runs automatically when the database is created. So such changes will not normally be made.

The easiest way to implement such schema changes is to either delete the App's data or uninstall the app. A third, simple way, if the onUpgrade method has been written to drop the tables and then call the onCreate method , is to cause the onUpgrade method to run by increasing the database version number.

Note that all three of the above methods will result in the loss of data. The first two delete the database causing it to be recreated. The database itself will not be deleted with the third, rather the specified tables are dropped (delete) and then recreated.

If loss of existing data would be an issue, then you can use the onUpgrade method to implement changes that preserve the data. For example, you could use the ALTER TABLE tablename ADD COLUMN your_new_column column_type (you can use DEFAULT value to set the columns to default values).

eg

 ALTER TABLE mytable ADD COLUMN mynewcolumn TEXT DEFAULT 'nothing as yet' 

would Add a column called mynewcolumn , with a column type(affinity) of TEXT, to the table named mytable and all rows would have the value nothing as yet .

Note! all the above assume that you are using a Database Helper (ie a subclass of the SQLiteOpenHelper class ((ie it extends SQLiteOpenHelper))).

Alternative issue

If you are using ALTER to add a column there are some restrictions.

You cannot add a column that has UNIQUE or PRIMARY INDEX constraints. As your column name indicates an id column then you may well have tried something like

String youraltersql = "ALTER TABLE "+TRANSACTIONS_TABLE_NAME+" ADD COLUMN " + SUB_CATEGORY_ID_COL + " INTEGER PRIMARY KEY"

this would not work, due to INTEGER PRIMARY KEY (same if you have AUTOINCREMENT).

SQL As Understood By SQLite - ALTER TABLE

You Updated your table while adding new Column after table crated, so you have to Implement override method, have look this :

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // If you need to add a column
  if (newVersion > oldVersion) {
     db.execSQL("ALTER TABLE "Your Table name"ADD COLUMN "new column "INTEGER DEFAULT 0");
  }
}

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