Identifying datatype of a column in an SQLite Android Cursor

后端 未结 4 2166
小鲜肉
小鲜肉 2020-12-07 01:12

Is there any way to identify the datatype of a column in a cursor in Android. The cursor object has a number of methods to get the columnname, column value.

I want t

4条回答
  •  暖寄归人
    2020-12-07 01:42

    Per the SQLite documentation (http://www.sqlite.org/datatype3.html) columns in SQLite don't have a datatype -- the values in those columns do.

    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.

    If you're using API level 11 or above then the cursor supports getType() (see http://developer.android.com/reference/android/database/AbstractWindowedCursor.html#getType(int)).

    If you're using an earlier API level, and you know that all the results in a given cursor come from the same table then you could do something like (untested):

    // Assumes "cursor" is a variable that contains the cursor you're
    // interested in.
    
    String tableName = "..."; // The name of the table
    SQLiteDatabase db = cursor.getDatabase();
    String[] names = cursor.getColumnNames();
    
    for (name : names) {
        Cursor typeCursor = 
            db.rawQuery("select typeof (" + name + ") from " + tableName;
        typeCursor.moveToFirst();
        Log.v("test", "Type of " + name + " is " + typeCursor.getString(0);
    }
    

    But that will (I expect) fail if the passed in cursor was (for instance) the result of a db.rawQuery() call that joined two or more tables.

提交回复
热议问题