HTML5 WebSQL Demo
HTML
<div id="example">
<div>
<label for="fullName">Name:</label>
<input type="text" id="fullName" />
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" />
<input type="text" id="rowid" />
</div>
<div>
<input type="button" id="setStorage" value="Save to DB" />
<input type="button" id="loadStorage" value="Load From DB" />
</div>
<div>
<input type="button" id="clearFields" value="Clear Fields" />
<input type="button" id="clearStorage" value="Clear DB" />
</div>
</div>
CSS
label {
float: left;
min-width: 5em;
}
label:after {
clear:both;
}
input[type="button"] {
width: 12.5em;
margin: 1em 1em 0 0;
}
JavaScript
if(typeof openDatabase === "undefined") {
$("body").html("<h2>Aw, shucks.<br/>Your browser doesn't support Web SQL</h2>");
} else {
// set up DB
var db = openDatabase("yaysql", "1.0", "SQL in the web - my worst nightmare", 1 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql(
"create table if not exists " +
"example(name string, location string)",
[],
function () {
console.log("table created...maybe :-)");
}
);
});
var $name = $("#fullName");
var $loc = $("#location");
var store = {
saveToDB: function () {
var vals = this.getInputValues();
db.transaction(function (tx) {
tx.executeSql(
"INSERT INTO example (name, location, rowid) VALUES (?, ?, ?)",
[vals.fullName, vals.location, vals.rowid],
function () {
console.log("Saved");
}
);
});
},
loadFromDB: function (cb) {
db.transaction(function (tx) {
tx.executeSql(
"SELECT name, location, rowid FROM example",
[],
function (tx, results) {
if (!results.rows.length) {
alert("Nothing is stored in the DB currently.");
return;
}
// we're only using the first row...example cheating FTW
cb(results.rows.item(1).name, results.rows.item(1).location, results.rows.item(1).rowid);
}
);
});
},
clearFields: function () {
$name.val("");
$loc.val("");
},
clearDB: function () {
db.transaction(function (tx) {
tx.executeSql(
...