Getting the type of a column in SQLite

前端 未结 2 560
无人及你
无人及你 2020-12-03 06:14

My mate made the database for my Android app. For example, one of the tables is created like this:

CREATE TABLE table1(
    id_fields_starring INTEGER PRIMAR         


        
相关标签:
2条回答
  • 2020-12-03 06:16

    For those of you looking to do this programmatically in Xamarin perhaps (like me) you can execute the PRAGMA query against a SQLiteConnection as follows:

    connection.Query<SqliteColumninfo>($"PRAGMA table_info({tableName})");
    

    I couldn't find an object defined in the PCL Sqlite package for collecting the result so I created a class to collect the aforementioned components:

    public class SqliteColumninfo
    {
       public string Cid { get; set; }
       public string Name { get; set; }
       public string Type { get; set; }
       public int NotNull { get; set; }
       public int Dflt_Value { get; set; }
       public int PK { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-03 06:22

    Calling:

    PRAGMA table_info(table1);
    

    will dump the table information, e.g.

    cid|name                 |type    |notnull |dflt_value |pk
    0  |id_fields_starring   |INTEGER |0       |           |1
    1  |fields_descriptor_id |INTEGER |1       |           |0
    2  |starring_id          |INTEGER |1       |           |0
    3  |form_mandatory       |INTEGER |1       |1          |0
    4  |form_visible         |INTEGER |1       |1          |0
    

    and simply find the row in the cursor with notnull=1 and dflt_value=1


    Edit:

    To list all columns defined as INTEGER NOT NULL DEFAULT 1 this would work (helper is your instance of SQLiteOpenHelper):

    SQLiteDatabase db = helper.getWritableDatabase();
    Cursor cursor = db.rawQuery("PRAGMA table_info(table1)", null);
    try {
        int nameIdx = cursor.getColumnIndexOrThrow("name");
        int typeIdx = cursor.getColumnIndexOrThrow("type");
        int notNullIdx = cursor.getColumnIndexOrThrow("notnull");
        int dfltValueIdx = cursor.getColumnIndexOrThrow("dflt_value");
        ArrayList<String> integerDefault1NotNull = new ArrayList<String>();
        while (cursor.moveToNext()) {
            String type = cursor.getString(typeIdx);
            if ("INTEGER".equals(type)) {
                // Integer column
                if (cursor.getInt(notNullIdx) == 1) {
                    // NOT NULL
                    String defaultValue = cursor.getString(dfltValueIdx);
                    if ("1".equals(defaultValue)) {
                        integerDefault1NotNull.add(cursor.getString(nameIdx));
                    }
                }
            }
        }
        System.out.println("integerDefault1NotNull now contains a list of all columns " +
                " defined as INTEGER NOT NULL DEFAULT 1, " + integerDefault1NotNull);
    } finally {
        cursor.close();
    }
    
    0 讨论(0)
提交回复
热议问题