Here’s some code from an older project… I did a few find and replaces so I may have introduced an error or five but it should get you started. Get this to working first and then expand the sql statements to fit your needs.
// this function would open the database,
function sqlInit()
{
if(window.sqlDB != null)
return;
window.sqlDB = window.openDatabase("sqlContracts", "1.0", "sqlContracts", 2 * 1024 * 1024);
if(window.sqlDB === null)
{
console.log("Error creating contract database! This is required functionality and is not available on your device. We will be quietly exiting now.");, {
exit(-1);
}
else
{
sqlCreateTable();
}
}
// this creates the table
function sqlCreateTable()
{
var db = window.sqlDB;
// rec_id, channel, type, title, text, when, contact
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS contracts (rec_id UNSIGNED BIG INT PRIMARY KEY ASC, msg_when TEXT, contract_read INTEGER, contract_text TEXT)",
[], sqlNullHandler, sqlOnError);
tx.executeSql("CREATE UNIQUE INDEX IF NOT EXISTS unique_id ON contracts (rec_id)",
[],
sqlOnSuccess,
sqlOnError);
});
}
// this truncates the table thereby deleting all Contracts
function sqlTruncateTable()
{
var db = window.sqlDB;
db.transaction(function(tx)
{
tx.executeSql("DELETE FROM contracts WHERE rec_id > 0", [],
function(tx, rs) {
console.log("Table was truncated!");
},
sqlOnError);
});
}
// when called, this will drop the messages table
function sqlDropTable()
{
var db = sqlDB;
db.transaction(function(tx) {
tx.executeSql('DROP INDEX IF EXISTS unique_id', [], sqlOnSuccess, sqlOnError);
tx.executeSql('DROP TABLE IF EXISTS contracts', [],
function(tx, rs) {
$('#fetch-result').html("Table was truncated!");
sqlOnSuccess(tx, rs);
},
sqlOnError);
});
}
function sqlCountAllRecords(callback)
{
var db = window.sqlDB;
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM contracts', [], function (tx, results) {
if(typeof callback === "function")
callback(results.rows.length);
});
});
return(count);
}
function sqlGetRecordByID(rec_id, callback)
{
var db = window.sqlDB;
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM contracts WHERE rec_id=?', [rec_id],
function (tx, results) {
for (var i=0; i<results.rows.length; i++)
{
var row = results.rows.item(i);
if(typeof callback === "function")
callback( row );
break;
}
}, sqlOnError);
});
}
function dummyFunction(row)
{
rowContract = row;
}
//these are the static/core error/success functions
function sqlOnError(tx, e)
{
console.log("There has been a database error: " + e.message);
}
function sqlOnSuccess(tx, r)
{
// re-render the data.
// console.log("r contains: ");
// console.dir(r);
// console.log("tx contains: ");
// console.dir(tx);
// sqlListAllContracts(loadContracts);
}
function sqlNullHandler(tx, e) {}
// this adds any new Contract to the database
// rec_id, contract_when, contract_read, contract_text
function sqlAddRecord(rec_id, contract_when, contract_read, contract_text)
{
var db = window.sqlDB;
var read = 0; // all new records are unread (updated record later)
var xwhen = String(when);
xwhen = xwhen.trim();
var msg_when = xwhen.replace(" ", "T");
db.transaction(function(tx)
{
var addedOn = new Date();
// rec_id, contract_when, contract_read, contract_text
tx.executeSql("INSERT OR REPLACE INTO contracts(rec_id, contract_when, contract_read, contract_text) VALUES (?,?,?,?)",
[rec_id, contract_when, contract_read, contract_text],
sqlOnSuccess,
sqlOnError);
});
}
function sqlTotalExpired(days, callback)
{
var db = window.sqlDB;
var contract_when = contract_when_string(days); // today's date -n days
var expired = new Date(contract_when); // convert to this date
var query = "SELECT * FROM contracts WHERE (contract_when <= datetime('now', '-" +days +" day'))";
db.transaction(function(tx)
{
tx.executeSql(query, [], function(tx, rs) {
if(typeof callback === "function")
callback(rs.rows.length);
}, sqlOnError);
});
}
// this gets called VERY early in the startup and transaction may not be initialized
function sqlFindFirst(callback)
{
if(window.sqlDB === null)
return;
var db = window.sqlDB;
var query = "SELECT MIN(rec_id) AS first_msg FROM contracts";
db.transaction(function(tx)
{
tx.executeSql(query, [], function(tx, rs) {
if(typeof callback === "function")
var first_msg = 0;
if(rs.rows.length > 0)
{
first_msg = rs.rows.item(0).first_msg;
}
if(typeof callback === "function")
callback(first_msg);
}, sqlOnError);
});
}
// this deletes an Contract by rec_id
function sqlDeleteRecord(rec_id, callback)
{
var db = window.sqlDB;
db.transaction(function(tx)
{
tx.executeSql("DELETE FROM contracts WHERE rec_id=?", [rec_id],
function(tx, rs) {
if(typeof callback === "function")
callback(rs);
},
sqlOnError);
});
}
//this marks an Contract as read using the rec_id
function sqlMarkRead(rec_id, callback)
{
var db = window.sqlDB;
db.transaction(function(tx)
{
tx.executeSql("UPDATE contracts SET contract_read=1 WHERE rec_id=?", [rec_id],
function(tx, rs) {
callback(rs);
},
sqlOnError);
});
}
qlfunction getAllRecords()
{
var db = window.sqlDB;
// alert("Executing Query Transaction.");
db.transaction(function(tx)
{
tx.executeSql("SELECT * FROM contracts ORDER BY contract_when DESC", [],
sqlOnSuccess,
sqlOnError);
});
}
function contract_when_string(days)
{
var minus_days = parseInt(days, 10);
minus_days = (1000 * 60 * 60 * 24 * minus_days);
now = new Date();
now.setTime(now.getTime() - minus_days);
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
function localDateStr(dateObj)
{
// let's get a human friendly date
var strDate = "" + new Date(dateObj);
var parseDate = strDate.split(" ", 5);
var msg_when = parseDate[0] +" " +parseDate[1] +" " +parseDate[2] +" " +parseDate[3] +" " +parseDate[4];
return(msg_when);
}
// state: 0 - unread, 1 = read
function getUnreadRecords(contract_state, callback)
{
var db = window.sqlDB;
// console.log("getUnreads db = " +db);
if(db == null)
{
console.log("db not initialized");
return;
}
db.transaction(function(tx)
{
tx.executeSql("SELECT * FROM contracts WHERE contract_read == ?", [contract_state],
function(tx, rs) {
if(typeof callback === "function")
callback(rs.rows.length);
else
return(rs.rows.length);
},
sqlOnError);
});
}