Search code examples
javascriptsqlsqlitesql.js

Permanently save SQL database created using Javascript


I have created a SQL database using Javascript using the below function.

function myFunction()
{
var db = new SQL.Database();
db.run("CREATE TABLE test (col1, col2);");
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

stmt.bind({$start:1, $end:2});
while(stmt.step()) { 
    var row = stmt.getAsObject();
   }
}

When I execute the function, it works perfectly. After commenting the 4th and 5th lines I expect to retrieve the values which I previously stored in the created database. But it creates a new database every time. Kind of a temporary database. How to fetch the previously inserted values, without creating the DB each and every time.

Note : Import

<script src='sql.js'></script>

Download SQL.js

 document.getElementById("text1").value = row.col1;

Solution

  • As stated at https://github.com/kripken/sql.js/,

    It uses a virtual database file stored in memory, and thus does’nt persist the changes made to the database. However, it allows you to import any existing sqlite file, and to export the created database as a javascript typed array.