简体   繁体   中英

Can you create your own Enum type in SQLite in Android Studio?

Hello I'm working on a Management Restaurants project on Android Studio using Java, and since I have 6 types of categories , I want to group them on a specific type in my Database table like we do in MySQL Enum type, and of course access to them later.
Here's my table code on Java, and I'm using SQLite as a database:

public static final String CREATE_RESTAURANT_TABLE_ =
            "CREATE TABLE  " + RESTAURANT_TABLE + "(" +
                    ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                    NAME + " TEXT " +
                    CITY + " TEXT " +
                    CATEGORY + "TEXT" +
                    PHONE_NUMBER + "TEXT"  +
                    LAT + "TEXT" +
                    LON + " TEXT );";

There is no ENUM data type in SQLite, but even if there was one it would not be the best way to define this column.
What if you want to add a new category? You would have to redefine the enum values in the table's definition and this is not possible in SQLite unless you recreate the table (as you can find here ).

The proper design in this case is to create a table categories like:

CREATE TABLE categories(id INTEGER PRIMARY KEY, category TEXT);

and store all the categories there:

INSERT INTO categories(category) VALUES 
  ('category1'),   ('category2'), ....,   ('categoryn');

and in your RESTAURANT_TABLE define a column that references the column id of categories :

public static final String ID_CATEGORY = "id_category";
public static final String CREATE_RESTAURANT_TABLE_ =
            "CREATE TABLE  " + RESTAURANT_TABLE + "(" +
                    ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                    NAME + " TEXT," +
                    CITY + " TEXT," +
                    ID_CATEGORY + " INTEGER REFERENCES categories(id)," +
                    PHONE_NUMBER + " TEXT,"  +
                    LAT + " TEXT," +
                    LON + " TEXT);";

In your SQLiteOpenHelper class you must enable foreign key constraints by overriding onConfigure() like this:

@Override
public void onConfigure(SQLiteDatabase db) {
    db.setForeignKeyConstraintsEnabled(true);
}

Now, in the column id_category of the restaurants table you will store ids which are references to the categories that you have in the categories table.
You can add new categories in categories without any problem.

When you query the table restaurants and you want to retrieve each row's category you must join the 2 tables:

SELECT r.id, r.name, r.city, c.category, r.phone_number, r.lat, r.long
FROM restaurants AS r INNER JOIN categories AS c
ON c.id = r.id_category

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