This can't be a proper question to ask here, but I am a bit confused about How & which database to use with my phonegap application (made with HTML5 + Javascript+CSS)
If anyone having any Reference link or any Idea of'
How I can use database in this application?
Thanks in advance.
You can use SQLite wrapper.
Plugin Link
It's very easy to use.
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function(res) {
console.log("PRAGMA res: " + JSON.stringify(res));
});
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
db.transaction(function(tx) {
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
Detailed documentation available in the link.
If you need small data to save like few words, then you can use localStorage.
Related
I'm new to Cordova & Sqlite but I wrote some code and I can't figure out what is wrong with it? Any suggestions?
I always get the following output from the Javascript debugger:
Click to see error messages
<script type="text/javascript">
// Wait for Cordova to load
document.addEventListener('deviceready', onDeviceReady, false);
var output = document.getElementById('outputField');
// Cordova is ready
function onDeviceReady() {
window.sqlitePlugin.openDatabase({ name: 'test.db', location: 2 }, function (db) {
output.innerHTML += '</br> - Database created/opened';
db.transaction(function (tx) {
tx.executeSql(tx, "CREATE TABLE localStorage2 IF NOT EXISTS (key UNIQUE, value)");
});
output.innerHTML += '</br> - Table localStorage2 Created';
storeValue(db, 'localStorage2', 'testKey', 'testValue');
output.innerHTML += '</br> - Insert dummy value';
output.innerHTML += '</br> ' + readValue(db, 'localStorage2', 'testKey');
});
}
function storeValue(db, table, key, value) {
db.transaction(function (tx) {
tx.executeSql(tx, 'INSERT INTO ' + table + ' (key,value) VALUES ("' + key + '","' + value + '")');
});
}
function readValue(db, table, key) {
db.transaction(function (tx) {
return db.executeSql(tx, 'SELECT * FROM ' + table + ' WHERE key="' + key + '"');
});
}
</script>
If you are testing a new plugin, library, … whatever, the best way is to read the docs, play a little bit with the examples and expand it step by step for your needs.
The SQLite plugin is event driven, that means, that you have to wait until the job is done.
You are doing it this way and this don't work:
var the_result = mySQL_Job();
function mySQL_Job(){
db.readTransaction(function(tx) {
return db.executeSql(…);
});
}
The right way is:
mySQL_Job();
function mySQL_Job(some_values){
tx.executeSql("SELECT * FROM myTable", [], function(tx, res) {
//Here goes your result handling, like inserting values in your html
}, function(error) {
console.log('SQLite error: ' + error.message);
});
}
This you have to do for every sql job, please see the docs at: https://github.com/litehelpers/Cordova-sqlite-storage
If you have a lot of queries then it is a good idea to use promises: How to compact SQL instructions in Cordova?
I have one requirement to start the SP workflow through JavaScript. For this, i have wrote some lines of code to start the workflow.But I am getting a Subscription failed error due to undefined object. This is occuring at ExcecuteasyncQuery method. So i didn't get which object returns the undefined value. My code is shown below.
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.workflowservices.js"> </script>
<script type="text/javascript">
var subID = "3debdbad-db52-4586-87e1-40e4db581da5";
function GetCurrentItemID()
{
var ctx = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
for (item in selectedItems)
{
var itemId = selectedItems[item].id;
startWorkflow(itemId, subID);
}
}
function startWorkflow(itemID, subID) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
var subscription = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subID);
context.load(subscription);
context.executeQueryAsync(
function(sender, args){
alert("Subscription load success. Attempting to start workflow.");
var inputParameters = {};
wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem
(subscription, itemID, inputParameters);
context.executeQueryAsync(
function(sender, args){ alert("Successfully starting workflow."); },
function(sender, args){
alert("Failed to start workflow.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
},
function(sender,args){
alert("Failed to load subscription.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
</script>
I am calling the GetCurrentItemID() function at the button click. But at that time, i am getting the following error.
Failed to load subscription
Invalid Request
Undefined
Could any one please help me to sort out this issue. Thanks in advance.
According to the script and the error message,
I suggest you check whether the “subscription” and “itemId” objects hold the proper values.
What’s more, you can take a look at the two links below about how to start workflow using JavaScript Client Object Model:
http://usamawahabkhan.blogspot.com/2013/07/start-workflow-sharepoint-2010.html
https://sharepoint.stackexchange.com/questions/87015/solved-start-a-workflow-of-the-host-web-via-sharepoint-app-and-jsom
Feel free to reply with the test result or if there are any progress.
Building on the solutions provided by others, here's the code I was able to use. NOTE: You need to have your workflow set to "Allow this workflow to be started manually."
/**
* Starts a SharePoint 2013 Workflow on a particular list item.
* Params:
* workflowName: The name of the Workflow
* listGUID: the GUID of the list
* itemId: the ID of the list item
*/
function startListWorkflow(workflowName, listGUID, itemId){
SP.SOD.executeFunc("sp.js", "SP.ClientContext" , function(){
SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'));
SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager",
function(){
var ctx = new SP.ClientContext.get_current(),
wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()),
wfSubs = wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(listGUID);
ctx.load(wfSubs);
ctx.executeQueryAsync(function () {
wfsEnum = wfSubs.getEnumerator();
while (wfsEnum.moveNext()) {
var wfSub = wfsEnum.get_current();
if (wfSub.get_name() === workflowName) {
var initiationParams = {};
wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, itemId, initiationParams);
ctx.executeQueryAsync(
function (sender, args) {
console.log("Successfully started workflow.");
},
function (sender, args) {
console.log("Failed to start the workflow.");
console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
}
},function(e){
console.error(e)
});
}
);
});
}
I am new to Sqlite and java script. I am getting struck with inserting and selecting multiple rows in sqlite database. Can any one help me to that how can I insert and select multiple rows ? my code is as follows,
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1"); // check #18/#38 is fixed
alert("insertId: " + res.insertId + " -- should be valid");
db.transaction(function(tx) {
tx.executeSql("SELECT data_num from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
alert("res.rows.item(0).data_num: " + res.rows.item(i).data_num + " -- should be 100");
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
And How can i insert values from one java script function and how can i retrieve values from another function is it possible? if yes can anyone suggest some good tutorials or explain the same.
I've tried several different commands for clearing my Web SQL Database and none of them work. Just to show you I've assembled all of them into one overkill function. What am I missing?
/** Drop Table from Database - Fix This **/
function overKill(tablename){
var query = "DELETE FROM " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
var query = "DELETE * FROM " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
var query = "DROP TABLE " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
}
This worked for me
tx.executeSql("DROP TABLE foo",[],
function(tx,results){console.log("Successfully Dropped")},
function(tx,error){console.log("Could not delete")}
);
Worked for me:
tx.executeSql('DELETE FROM FormRecords');
Moreover, you cannot delete a Web SQL database.
DELETE * FROM...
does not make sense. use DELETE FROM instead
You last variant is correct. Just for testing you can open your web resourse by Chrome. Then open Resourses -> Web SQL where you can type DROP TABLE TABLENAME and check if everething is right.
The follow code should works well:
var db = openDatabase(databaseName, "0.1", description, size)
var db.transaction(function (t) {
t.executeSql("DROP TABLE objectTable",[],
function(t,results){
console.error("Table Dropped")
},
function(t,error){
console.error("Error: " + error.message)
}
)
})
In my HTML5, i have a for loop which calls a function to insert into a database. I need this function to be inside a single transaction.
function Ins(id){
db.transaction(function(tx){
tx.executeSql('insert into Product(id) values(?);', [iName], function() {}, function() { });
});
}
The for loop
db.transaction(function(tx){tx.executeSql("BEGIN",[]);});
for (intCountLine=1;intCountLine<=1000;intCountLine++)
{
Ins(intCount);
}
db.transaction(function(tx){tx.executeSql("COMMIT",[]);});
You can see, i have the transaction begin & commit, but i assume when it calls the INS function, it would open a new transaction and close it, everytime it is called. How do i make sure that doesn't happen.
googled it but could not find it... throw me some light here....
May be this will works. Use insert select union all instead of creating 1000 insert statements. But this can insert only 500 rows at a time. Here is the code which i worked on, do a test on Google chrome i am sure it works.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
var j=1;
var i=1;
var quer="";
db.transaction(function(tx){tx.executeSql("CREATE TABLE IF NOT EXISTS LOGS (ID INTEGER PRIMARY KEY ASC, todo TEXT)",[]);});
db.transaction(function(tx){tx.executeSql("delete from logs",[]);});
txquer();
showMsg();
function txquer()
{
quer="insert into logs ";
for(i=j;i<=j+498;i++)
{
quer+=" select "+i+",'test' union all";
}
quer+=" select "+i+",'test' ; ";
j=i+1;
db.transaction(
function(tx){
tx.executeSql(quer,[]);
}
);
}
function showMsg(){
db.transaction(function (tx) {
tx.executeSql('SELECT count(*) todo FROM LOGS', [], function (tx, results) {
var len = results.rows.item(0).todo;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
}, null);
});
}