Created
June 6, 2017 14:51
-
-
Save s0ren/22ba7f491898880f9f4fe6c4b0b88c1c to your computer and use it in GitHub Desktop.
Sqlite in html/javascript on clientside web.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<script src='js/sql.js'></script> | |
<script> | |
// from https://github.com/kripken/sql.js/wiki/Persisting-a-Modified-Database | |
function toBinArray (str) { | |
var l = str.length, | |
arr = new Uint8Array(l); | |
for (var i=0; i<l; i++) arr[i] = str.charCodeAt(i); | |
return arr; | |
} | |
// from https://github.com/kripken/sql.js/wiki/Persisting-a-Modified-Database | |
function toBinString (arr) { | |
var uarr = new Uint8Array(arr); | |
var strings = [], chunksize = 0xffff; | |
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want | |
for (var i=0; i*chunksize < uarr.length; i++){ | |
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize))); | |
} | |
return strings.join(''); | |
} | |
// from https://github.com/kripken/sql.js#examples | |
//Create the database | |
var db = new SQL.Database(toBinArray(localStorage.getItem('minDB'))); | |
// Run a query without reading the results | |
db.run("CREATE TABLE IF NOT EXISTS test (col1 primary key, col2);"); | |
// Insert two rows: (1,111) and (2,222) | |
db.run("INSERT OR REPLACE INTO test VALUES (?,?), (?,?)", | |
[1, "1ste " + new Date().toLocaleString(), | |
2, "2den " + new Date().toLocaleString()]); | |
// Prepare a statement | |
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end"); | |
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111} | |
// Bind new values | |
stmt.bind({$start:1, $end:2}); | |
while(stmt.step()) { // | |
var row = stmt.getAsObject(); | |
// [...] do something with the row of result | |
console.log(JSON.stringify(row)); | |
} | |
localStorage.setItem('minDB', toBinString(db.export()) ); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment