Last active
May 2, 2017 10:58
-
-
Save ilgianfra/9b3c4f1492745d818618 to your computer and use it in GitHub Desktop.
SqliteService is an angular service in order to use the webSQL in your browser and sqlite DB in your device
This file contains 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
(function(angular){ | |
angular.module('Service.Sqlite',[]) | |
.factory('SqliteService', function($cordovaSQLite){ | |
var db = null; | |
function createDB(){ | |
var queryCreate = "CREATE TABLE IF NOT EXISTS diary ( \ | |
date INTEGER, \ | |
picture text, \ | |
activities text \ | |
)"; | |
if (window.cordova) { | |
db = $cordovaSQLite.openDB({ name: "my.db" }); //device | |
$cordovaSQLite.execute(db, queryCreate, []).then(function(res) { | |
console.log(res); | |
}, function (err) { | |
console.error(err); | |
}); | |
}else{ | |
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser | |
db.transaction(function(tx) { | |
tx.executeSql(queryCreate, | |
[], | |
function(tx, res){console.log(res, 'DB CREATED');}, | |
function(tx, err){} | |
); | |
}); | |
} | |
} | |
function executeQuery(query, values, cb){ | |
cb = cb || function(){}; | |
if (window.cordova) { | |
$cordovaSQLite.execute(db, query, values).then(function(res) { | |
var length = res.rows.length; | |
var results = []; | |
for (var i = 0; i <= length-1 ; i++) { | |
console.log(res.rows.item(i)); | |
results.push(res.rows.item(i)); | |
}; | |
return cb(results, length); | |
}, function (err) { | |
console.error(err); | |
return cb(err); | |
}); | |
} else { | |
db.transaction(function(tx) { | |
tx.executeSql(query, | |
values, | |
function(tx, res){console.log(res); return cb(res.rows)}, | |
function(tx, err){console.log(err); return cb(err)} | |
); | |
}); | |
} | |
} | |
function dropTable(table){ | |
var drop = 'DROP TABLE ' + table; | |
executeQuery(drop, []); | |
} | |
return{ | |
createDB: createDB, | |
executeQuery: executeQuery, | |
dropTable: dropTable | |
}; | |
}); | |
})(angular); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment