What's the simplest way to import an SQLite SQL file into a WEB SQL Database

后端 未结 2 959
醉话见心
醉话见心 2020-12-15 01:27

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 cr

2条回答
  •  一个人的身影
    2020-12-15 01:47

    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!");
      }
    }
    

提交回复
热议问题