Uriel Arvizu
Uriel Arvizu

Reputation: 1916

Cordova Sqlite plugin inserts entries with null values

I'm implementing the Cordova Sqlite plugin in a Ionic project, so far I've been able to create a database and table and make queries following the functions available through the ngCordova implementation.

I noticed there's a insertCollection function available, which I tried to test, I passed an array to it and even though the inserts are made, the entries are made with null.

This my example table definition:

CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)

I filled an array like this:

for(var i = 0; i < 250000; i++){
  var index = i + 1;
  firstname = firstname + ' ' + index;
  var entry = {
    'firstname' : firstname,
    'lastname' : lastname
  };
  $scope.insertArray.push(entry);
}

And then made the insert like this:

$cordovaSQLite.insertCollection($rootScope.db, $scope.insertQuery, $scope.insertArray).then(function(res) {
  console.log(res);
}, function (err) {
  console.error(err);
});

Where insertQuery is the following:

INSERT INTO people (firstname, lastname) VALUES (?,?)

I made a select like this:

  $scope.select = function() {
    $scope.results = [];
    var query = "SELECT firstname, lastname FROM people";
    $cordovaSQLite.execute($rootScope.db, query).then(function(res) {
      if(res.rows.length > 0) {
        console.log('select was successful ' + res.rows.length + ' entries');

        for(var i = 0; i < $scope.maxItemsToShow; i++){
          $scope.results.push(res.rows.item(i));
        }

      } else {
        console.log("No results found");
      }
    }, function (err) {
      console.error(err);
    });
  }

I try to display the results on a ion-list but the values in firstname and lastname are null for all the items.

What is causing this problem?

Upvotes: 1

Views: 590

Answers (1)

NineBerry
NineBerry

Reputation: 28499

The function insertCollection expects an array of arrays, not an array of records. The inner array must contain the values to insert in the order that the question marks (as place holders for the values) appear in the sql statement.

So you need to write:

for(var i = 0; i < 250000; i++){
  var index = i + 1;
  firstname = firstname + ' ' + index;
  var entry = [firstname, lastname];
  $scope.insertArray.push(entry);
}

Upvotes: 1

Related Questions