selectionArgs in SQLiteQueryBuilder doesn't work with integer values in columns

后端 未结 3 1079
忘了有多久
忘了有多久 2021-01-01 00:38

I\'m trying to select some data from database and I have two slices of code to do it:

cursor = builder.query(db,
                    new String[]{\"col1\", \         


        
3条回答
  •  梦谈多话
    2021-01-01 01:15

    According to SQLite documentation,

    Any column in an SQLite version 3 database, except an INTEGER PRIMARY KEY column, may be used to store a value of any storage class.

    In context of my case, that means that we can't be sure what data type will be stored in columns. If you can control and convert data types when they're putting into database - you can convert id values to TEXT when adding data to database and use selectionArgs easily. But it's not an answer for my question, because I have to deal with database content as is.

    So, possible solutions:

    a) embed integer values in selection string without wrapping them into ':

    cursor = builder.query(db,
                        new String[]{"col1", "col2", "col3"},
                        "id = " + getSID(db), null, null, null, null);
    

    b) cast values from selectionArgs: CAST(? as INTEGER) or CAST(id AS TEXT). I think, converting column to TEXT is better solution, because right operand is always TEXT, but the left one can be anything. So:

    cursor = builder.query(db,
                        new String[]{"col1", "col2", "col3"},
                        "CAST(id AS TEXT) = ?", 
                        new String[]{getSID(db)}, null, null, null);
    

提交回复
热议问题