How to insert to into many to many relationships. SQLite

Kanayel

In my android app I have an SQLite database. with this structure:

PrivateList(idList INTEGER PRIMARY KEY, name TEXT, creationDate TEXT, active INTEGER, deactivationDate TEXT);

PrivateProduct (idProduct INTEGER PRIMARY KEY, description TEXT, quantity INTEGER, active INTEGER, additionDate TEXT);

List_Product(idList INTEGER NOT NULL, idProduct INTEGER NOT NULL, PRIMARY KEY (idList, idProduct), FOREIGN KEY(idList) REFERENCES PrivateList(idList), FOREIGN KEY(idProduct) REFERENCES PrivateProduct(idProduct));

I have an autogenerator list and elements using for to try the app:

localDB = new LocalDB(this, "localBD", null, 1);
        SQLiteDatabase sqLiteDatabase = localDB.getWritableDatabase();

        if (sqLiteDatabase != null){

            for (int i = 0; i < 10; i++){
                String a = "List" + i;
                String b = "Product" + i;
                Log.i("execfor", "INSERT INTO PrivateList (name, creationDate, active, deactivationDate) " + " VALUES ('" + a + "', CURRENT_TIMESTAMP, 1, null);");
                sqLiteDatabase.execSQL("INSERT INTO PrivateList (name, creationDate, active, deactivationDate) " + " VALUES ('" + a + "', CURRENT_TIMESTAMP, 1, null);");
                sqLiteDatabase.execSQL("INSERT INTO PrivateProduct (description, quantity, active, additionDate) " + " VALUES ('" + b + "', 3, 1, CURRENT_TIMESTAMP);");
                //sqLiteDatabase.execSQL("INSERT INTO List_Product (idList, idProduct) values ");//

            }

        }

But I can`t find the way to get rowIds from each list and product to insert both, idlist and idproduct, into List_Product.

Thank you in advance.

MikeT

The main change to facilitate grabbing the id's would be to swap from using execSQL to using insert as insert returns the id of the inserted row, execsql does not.

A little more on this here Using execSQL for INSERT operation in Android SQLite.

However, I'm not sure if you can pass CURRENT_TIMESTAMP via a ContentValues and it would result getting the current timestamp as opposed to just setting the value to the literal CURRENT_TIMESTAMP. You could use DEFAULT CURRENT_TIMEPSTAMP in the respective column definitions (as I have in the code below).

I'd suggest that you would not want a link between every list/product permutation (that would be 100 rows for you 10 List rows and 10 Product rows) as in real life you would probably not have such a scenario rather you'd have some links between the two. So in the code below I've randomly created links.

First some code from the Database Helper (for my convenience named SO45449914) for performing the inserts:-

public long insertListRow(String name,
                          int active) {
    ContentValues cv = new ContentValues();
    cv.put(LISTNAME_COL,name);
    cv.put(LISTACTIVE_COL,active);
    cv.put(LISTDEACTIVATIONDATE_COL,"");
    return this.getWritableDatabase().insert(PRIVATELISTTABLE,null,cv);
}

public long insertProductRow(String description,int quantity, int active) {
    ContentValues cv = new ContentValues();
    cv.put(PRODUCTDESCRIPTION_COL,description);
    cv.put(PRODUCTQUANTITY_COL,quantity);
    cv.put(PRODUCTACTIVE_COL,active);
    return this.getWritableDatabase().insert(PRIVATEPRODUCTTABLE,null,cv);
}

public void insertListProductLink(long listid, long productid) {
    ContentValues cv = new ContentValues();
    cv.put(LISTPRODUCTLIST_COL,listid);
    cv.put(LISTPRODUCTPRODUCT_COL,productid);
     if (this.getWritableDatabase().insertOrThrow(LISTPRODUCTTABLE,null,cv) <0) {
        //handle failed insert
    }
}

Notes - I've used class variables for all columns names. - Columns that have the current time stamp get this via the default, so there is no need to have a cv.put for those columns.

In the activity is the following code :-

        void doSO45449914() {
            SO45449914 dbhelper = new SO45449914(this);
            int loopcount = 10;
            long[] listids = new long[loopcount];
            long[] productids = new long [loopcount];


            for (int i=0; i < 10; i++) {
                listids[i] = dbhelper.insertListRow("a" + i,1);
                productids[i] = dbhelper.insertProductRow("b" + i,3,1);
            }

            Cursor csra = dbhelper.getWritableDatabase().query(SO45449914.PRIVATELISTTABLE,
                     null,null,null,null,null,null
            );
            Cursor csrb = dbhelper.getWritableDatabase().query(SO45449914.PRIVATEPRODUCTTABLE,
                    null,null,null,null,null,null
            );
            Log.d("SO45449914","Number of rows in LIST TABLE = " + csra.getCount());
            Log.d("SO45449914","Number of rows in PRODUCTS TABLE = " + csrb.getCount());
            for (long aid: listids) {
                Log.d("SO45449914","LIST ID from store = " + Long.toString(aid));
            }
            for (long bid: productids) {
                Log.d("SO45449914","PRODUCT ID from store = " + Long.toString(bid));
            }
            for (long lid: listids) {
                for (long prdid: productids) {
                    if ((Math.random() * 100) > 60) {
                        dbhelper.insertListProductLink(lid,prdid);
                        Log.d("SO45449914",
                                "Adding link between List id(" +
                                        Long.toString(lid) +
                                        ") and product id(" +
                                        Long.toString(prdid) +
                                        ")"
                        );
                    }
                }
            }

            csra.close();
            csrb.close();
        }

Exlapnation

The first few lines prepare long arrays based upon the number of Lists and products to be created (same number of both). Integer loopcount determines how many.

The first loop, inserts Lists and Products which use the insert method storing the returned id in the respective array element.

Two Cursors are then created for obtaining row counts, which are then written to the log. The id's as stored in the arrays are output to the log.

Two nested loops are then invoked with Products being the inner (not that it matters) and randomly (about 40% of the time) a row will be inserted into the link table. I've assumed random but you always easily adjust the algorithm to follow a pattern. It's if ((Math.random() * 100) > 60) { that determines whether or not to insert a link.

The two Cursors are then closed.

Results

Here are screen shots of the resultant tables :-

PrivateList Table

PrivateList Table

PrivateProduct Table

Private Product Table

List_Product Table

enter image description here

..... (44 rows in the List_Product table)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

SQLite one to many and many to many relationships between the tables

From Dev

Ebean and many-to-many relationships - how?

From Dev

How to upload an image to a form with many to many relationships?

From Dev

How to work with many has many through relationships

From Dev

how to work with many to many relationships in Microsoft access?

From Dev

How to query many to many relationships on django?

From Dev

Issue with many to many relationships

From Dev

SQLite insert function/method too many parameter arguments, how to refactor?

From Dev

How to build and insert a Many to Many association

From Dev

How to insert data in many to many relationship

From Dev

How to build and insert a Many to Many association

From Dev

SQLite, Many to many relations, How to aggregate?

From Dev

How to create a viewModel object for many-to-many relationships

From Dev

How to find associated records from 2 many to many relationships

From Dev

How to find records from 2 many to many relationships

From Dev

How to change the naming convention of Many-to-Many table relationships?

From Dev

Understanding Many-to-Many relationships in MongoDB and how to dereference collections

From Dev

How do I model multiple "many to many" relationships in Cassandra?

From Dev

How to create/update many-to-many relationships in a RESTful API

From Dev

How to find records from 2 many to many relationships

From Dev

How to find associated records from 2 many to many relationships

From Dev

Understanding Many-to-Many relationships in MongoDB and how to dereference collections

From Dev

How to evaluates complex many to many relationships in core data using predicate?

From Dev

How to differentiate a many-to-many relationships while designing a database?

From Dev

How to create objects inline for many to many relationships in Django?

From Dev

How to add many-to-many relationships through a form?

From Dev

JPA - how to prevent an unnecessary join while querying many to many relationships

From Dev

Many-to-many hierarchical relationships

From Dev

Many to many relationships MongoDB mongoose

Related Related

  1. 1

    SQLite one to many and many to many relationships between the tables

  2. 2

    Ebean and many-to-many relationships - how?

  3. 3

    How to upload an image to a form with many to many relationships?

  4. 4

    How to work with many has many through relationships

  5. 5

    how to work with many to many relationships in Microsoft access?

  6. 6

    How to query many to many relationships on django?

  7. 7

    Issue with many to many relationships

  8. 8

    SQLite insert function/method too many parameter arguments, how to refactor?

  9. 9

    How to build and insert a Many to Many association

  10. 10

    How to insert data in many to many relationship

  11. 11

    How to build and insert a Many to Many association

  12. 12

    SQLite, Many to many relations, How to aggregate?

  13. 13

    How to create a viewModel object for many-to-many relationships

  14. 14

    How to find associated records from 2 many to many relationships

  15. 15

    How to find records from 2 many to many relationships

  16. 16

    How to change the naming convention of Many-to-Many table relationships?

  17. 17

    Understanding Many-to-Many relationships in MongoDB and how to dereference collections

  18. 18

    How do I model multiple "many to many" relationships in Cassandra?

  19. 19

    How to create/update many-to-many relationships in a RESTful API

  20. 20

    How to find records from 2 many to many relationships

  21. 21

    How to find associated records from 2 many to many relationships

  22. 22

    Understanding Many-to-Many relationships in MongoDB and how to dereference collections

  23. 23

    How to evaluates complex many to many relationships in core data using predicate?

  24. 24

    How to differentiate a many-to-many relationships while designing a database?

  25. 25

    How to create objects inline for many to many relationships in Django?

  26. 26

    How to add many-to-many relationships through a form?

  27. 27

    JPA - how to prevent an unnecessary join while querying many to many relationships

  28. 28

    Many-to-many hierarchical relationships

  29. 29

    Many to many relationships MongoDB mongoose

HotTag

Archive