I use this function:
private _batch(stmts: any[]): Promise<any> {
let rv: Promise<any> = new Promise((resolve, reject) => {
let wincb = (dbrv: any) => {
resolve(dbrv);
};
let losecb = (tx: any, err: Error) => {
reject(err);
return false;
};
this._db.transaction((tx: any) => {
let nstmts = stmts.length;
for (let ix = 0; ix < nstmts; ix++) {
let sql:string;
let phs:any[];
if (Array.isArray(stmts[ix])) {
sql = stmts[ix][0];
phs = stmts[ix][1];
} else {
sql = stmts[ix];
phs = [];
}
tx.executeSql(sql, phs, undefined, losecb);
}
}, losecb, wincb);
});
return rv;
}
db is initialized like this:
if (win.sqlitePlugin) {
let openparms = {
name: _SQLITE_DB_NAME,
location: 2, // local backup
createFromLocation: 0
};
this._db = win.sqlitePlugin.openDatabase(openparms);
} else {
console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!');
this._db = win.openDatabase(_SQLITE_DB_NAME, '1.0', 'database', 5 * 1024 * 1024);
}
_batch
is called with an array of statements. They can either be a single string of SQL or an array beginning with the SQL and then containing placeholders. Called like so:
this._batch([
"CREATE TABLE version (version INT NOT NULL PRIMARY KEY)",
["INSERT INTO version (version) VALUES ($1)", [1]],
]);