Shudy
Shudy

Reputation: 7936

How to use int and increase it's value in different code lines

I have to initialize a sqlite database that have a structure like this:

Table: Family

Table: SubFamily

Table: Product

One family can have more than one subfamily and and the same for subfamilies with products.

So what i'm doing is:

int index_family = 1;
        int index_subfamily = 1;
        int index_product = 1;
//Productos Familia Pavimentos
        sqlDB.execSQL("INSERT INTO Family VALUES (" + index_family + ",'" + R.string.f1_pavimentos + "','" + R.string.f0_descripcion + "','" + R.drawable.color_pavimento + "');");

        sqlDB.execSQL("INSERT INTO SubFamily VALUES (" + index_subfamily + "," + index_family + ",'" + R.string.f1s1_nivelantes + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "');");
        sqlDB.execSQL("INSERT INTO Product VALUES (" + index_product + "," + index_subfamily + ",'" + R.string.f1s1p1_ni10 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
        sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 1) + "," + index_subfamily + ",'" + R.string.f1s1p2_ni80 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
        sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 2) + "," + index_subfamily + ",'" + R.string.f1s1p3_beL15 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
        sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 3) + "," + index_subfamily + ",'" + R.string.f1s1p4_beL30 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
        sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 4) + "," + index_subfamily + ",'" + R.string.f1s1p5_beP + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");

The problem is that the value of any index will increase all the time, and in a future will be added more products and families.

I want to know if there is some way more efficient that use for example this approach I did: (index_product + 1) ; (index_product + 2); ... without to use +N because in a future products (or families,subfamilies) will be added and deleted. And with a lot of products (more than 100) could be very dangerous this way.

Hope I explain my problem.

Upvotes: 0

Views: 63

Answers (1)

npinti
npinti

Reputation: 52185

Judging from what your boss is saying, it might make more sense to have a table for products, sub families and what have you and use foreign keys to take care of everything. Thus, each parent will have a foreign key pointing to all their children.

If you use an ORM, this would very likely be done automatically behind the scenes.

Also as @Weston mentioned, avoid string concatenation within SQL statements. As is your application is prone to SQL injection.

Upvotes: 1

Related Questions