Question

perhaps I'm missing something, but I need a client side database pre-populated with a load of data.

To test whether client side databases were up to the task, I created a few dummy tables with dummy data using the transaction.executeSql() method. But from what I can gather, it requires an executeSQL call for every single CREATE TABLE and INSERT INTO query. I'm lazy, and that seems like too much work to me.

I'm wondering...: I can create an SQLite table fairly quickly using an SQLite GUI. I've tried exporting an SQL file and running it all in one executeSQL statement but that just processes the first 'CREATE TABLE' bit none of the inserts.

Is there some special method of the transaction object that I'm not aware of for running multiple queries at once?

This is for Mobile Safari buy the way, which according to Apple uses an SQLite Database to power their client side database stuff.

Was it helpful?

Solution

i put all the sql code into a file with one command per line then used ajax to pull file and loop over each line executing the sql

tip: use the if not exists so you can call it every time to init your database

OTHER TIPS

On the commandline (in a linux box), use

sqlite3 myDatabase.sqlite .dump > myDatabase.sql

Now you have the sqlite file dumped to a plain sql file. It will contain the create table statements and the insert statements.

Then, some clientside code (will probably need some adjusting, but you'll get the idea)

First, grab the sql dump. (example using jQuery)

$.get('./dumps/myDatabase.sql', function(response) {
  // console.log("got db dump!", response);
  var db = openDatabase('myDatabase', '1.0', 'myDatabase', 10000000);
  processQuery(db, 2, response.split(';\n'), 'myDatabase'); 
});

The processQuery function process all the statements one by one, and silently ignores errors.

function processQuery(db, i, queries, dbname) {
    if(i < queries.length -1) {
      console.log(i +' of '+queries.length);
      if(!queries[i+1].match(/(INSERT|CREATE|DROP|PRAGMA|BEGIN|COMMIT)/)) {
        queries[i+1] = queries[i]+ ';\n' + queries[i+1];
         return processQuery(db, i+1, queries, dbname);
      }
      console.log('------------>', queries[i]);
      db.transaction( function (query){ 
        query.executeSql(queries[i]+';', [], function(tx, result) {
          processQuery(db, i +1, queries,dbname);  
        });          
      }, function(err) { 
      console.log("Query error in ", queries[i], err.message);                          
      processQuery(db, i +1, queries, dbname);   
      });
  } else {
      console.log("Done importing!");
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top