I'm unable to find a definitive answer for this, asynchronous web sql is really tripping me up. How does one execute a SELECT query using data based on a parent SELECT query? Here's a snippet I thought was working but really isn't:
db.transaction(function(tx){
tx.executeSql('SELECT a, b FROM mytable WHERE c=5', [], function(tx,results) {
var i = results.rows.length;
while(i--){
var votes = results.rows.item(i).a;
var marker = results.rows.item(i).b;
tx.executeSql('SELECT a FROM mytable WHERE c=?', [marker], function(tx,aresults) {
if(!aresults){
//do something
} else {
myScore += (votes*100)/aresults.rows.item(0).a;
}
}(marker));
}
nextFunction();
});
}, function(){onError});
Try this:
function firstQuery(){
db.transaction(function(tx){
tx.executeSql('SELECT a, b FROM mytable WHERE c=5', [],
function(tx,results) {
var i = results.rows.length;
while(i--){
secondQuery(results.rows[i]);
}
});
}, function(){onError});
}
function secondQuery(responseQuery){
var votes = responseQuery.a;
var marker = responseQuery.b;
db.transaction(function(tx){
tx.executeSql('SELECT a FROM mytable WHERE c=?', [marker], function(tx,aresults) {
if(!aresults){
//do something
} else {
myScore += (votes*100)/aresults.rows.item(0).a;
}
}(marker));
}, function(){onError});
}
Related
I want to return multiple rows as an array from a particular table in a database in WebSQL inside a javaScript function. Below is my code.
function getCustomerAccountDetails(){
var dataset;
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
dataset = results.rows;
});
});
return dataset
}
Any suggestions?
I just managed to do that using Return a COUNT from a WebSQL query in a javaScript function
According to the link, using jQuery it goes like this and it works! But I would like to have a javaScript answer.
function getCustomerAccountDetails(){
var defer = $.Deferred();
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
defer.resolve(results.rows);
});
});
return defer.promise();
}
function exampleThatUsesUserArray(data) {
//do something that uses count here
return data;
}
var dataArray = getCustomerAccountDetails();
$.when(dataArray).done(function(data) {
//now use count, could be you call another function that needs to use count,
//getCustomerAccountDetails();
alert(exampleThatUsesUserArray(data.length) + " Row Count");
for(var i = 0; i < data.length; i++){
alert((i+1) + "-" + data.item(i)['id'] + "-" + data.item(i)['firstname'] + "-"
+ data.item(i)['lastname'] + "-" + data.item(i)['phonenumber']);
}
//or assign it to another variable, or trigger an event that someone else in you app is listening for
});
I have here a broken function code that would retrieve a specific item from the SQLite database, my problem is I want to pass the value of the retrieved item to displayContent but I do not know how to do it, my code is only designed to retrieve a single row not multiple rows as the contents of SecondColumn are not identical. I am clueless right now.
Here is my code:
function ( content )
{
var displayContent;
db.transaction(function (tx) { tx.executeSql('SELECT FirstColumn FROM SampleTable WHERE SecondColumn = ?',[content]); });
}
Any additional ideas will be gladly accepted, I am stuck with this.
The tx.executeSql method takes a callback where you can then process the results of the query. Have a look here and you can see an example: http://www.tutorialspoint.com/html5/html5_web_sql.htm
As you can see there, they do the following:
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
In your case you'd probably do something like this:
function ( content )
{
db.transaction(function (tx) {
tx.executeSql('SELECT FirstColumn FROM SampleTable WHERE SecondColumn = ?',[content], function (tx, results) {
if (results.rows.length) {
var displayContent = results.rows.item(0).FirstColumn;
document.querySelector('...').innerHTML = ...; // Display something
}
});
});
}
If you want to try to wait for the query, have a look at this previous Stackoverflow question: HTML5 WebSQL: how to know when a db transaction finishes?
i'm trying to retrieve the data from the database for web application using webSQL ,but i'm unable to get the data from database. I'm very new to this. I tried like this
var DB_NAME = "database";
var DB_VERSION = "";
var DB_TITLE = "";
var DB_BYTES = 50 * 1024 * 1024;
var db = openDatabase(DB_NAME, DB_VERSION, DB_TITLE, DB_BYTES);
//Retrieve Rows from Table
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM Data;",
[],
function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
});
Thanks in Advance.
This is how i have done.. and this is working for me.
// global variables
var db;
var shortName = 'Books';
var version = '1.0';
var displayName = 'BooksDB';
var maxSize = 200000;//65535;
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
// this line tries to open the database base locally on the device if it does not exist, it will create it and return a database object stored in variable db
db = openDatabase(shortName, version, displayName,maxSize);
// this line clears out any content in the #lbUsers element on the page so that the next few lines will show updated content and not just keep repeating lines
$('#lbUsers').html('');
// this next section will select all the content from the User table and then go through it row by row appending the UserId FirstName LastName to the #lbUsers element on the page
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM books;', [], function(transaction, result) { if (result != null && result.rows != null) { for (var i = 0; i < result.rows.length; i++) { var row = result.rows.item(i); $('#lbUsers').append('<br>' + row.book_title + '. ' + row.book_isbn+ ' ' + row.book_price); } } },errorHandler); },errorHandler,nullHandler);
return;
alert('in list end');
}
// this is called when a successful transaction happens
function successCallBack() {
alert("DEBUGGING: success");
}
function nullHandler(){
alert('null handler');
};
There's a lot of code here, but the question has to do with the for loop at the bottom.
var dbo = openDatabase('xxx','1.0','myDatabase', 1048576);
var DropTableDeferred = new $.Deferred();
var CreateTableDeferred = new $.Deferred();
var InsertDeferred = new $.Deferred();
var SelectDeferred = new $.Deferred();
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'drop table myTable;'
,[]
,DropTableDeferred.resolve()
);
});
DropTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'CREATE TABLE IF NOT EXISTS myTable'
+ '(xxxID Integer NOT NULL PRIMARY KEY'
+ ',xxxName Varchar(128)'
+ ');'
,[]
,CreateTableDeferred.resolve()
);
});
});
CreateTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(1,'A')");
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(2,'B')");
myTrans.executeSql(
"INSERT INTO myTable(xxxID,xxxName) VALUES(3,'C')",
[],
InsertDeferred.resolve()
);
});
});
InsertDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'SELECT * FROM myTable',
[],
function(tx, result) {
SelectDeferred.resolve(result);
}
);
});
});
SelectDeferred.done(function(result) {
var X = $('#result-template').html();
var template = Handlebars.compile(X);
var data = [];
for(var i=0;i < result.rows.length; i++) {
data.push(result.rows.item(i));
}
$('ul').append(template(data));
});
Q: Do I need to build a data array in order to call template(data), or can I pass the result variable directly?
And by 'result variable', what I mean is: result.rows, or result.rows.item, or some other combination.
Yes the value has passed directly in my html&javascript only project. In the code below, I get the results of the Sql and filling a dropdown box's options.
function fillLectureFromDB(tx) {
tx.executeSql('SELECT * FROM LECTURE', [], successFill, errorFill);
}
function successFill(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
var elOptNew = document.createElement('option');
elOptNew.text = results.rows.item(i).code;
elOptNew.value = results.rows.item(i).code;
var elSel = document.getElementById('slExCode');
elSel.add(elOptNew, null);
}
}
IMHO you can, but to tell you the truth, it would've taken less time for you to try it out then to post the question. Just try:
$('ul').append(template(result.rows));
Here is the code
onError = function(tx, e) {
alert('Something unexpected happened: ' + e.message );
}
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
webdb.transaction(function(tx) {
tx.executeSql('SELECT * FROM colours',
[],
function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
},
onError);
});
/**
* the array looks like [[1,'red'],[2,'white'],[3,'black'] ...]
*/
var ColourStore = new Ext.data.ArrayStore({fields: ['key', 'val'],
data: colourArray});
The table "colours" contain colour name and hash code. And it was suppose to be use by a ExtJS Ext.data.ArrayStore then populate other drop downs on a massive form.
My problem is - I couldn't get the data back as an array. The variable "colourArray" is empty ... I know I hit some javascript closure , loop problem ... but just couldn't figure out how to get that inner loop value back. Try a lot of return -> return -> return function and more return. None of them works.
executeSQL is asynchronous. You need to create ColourStore in the function(tx,rs) callback function. If you need the data available globally, you can't init your app until executeSQL calls the callback function. Example:
Ext.onReady( function() {
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
var ColourStore;
webdb.transaction( function(tx) {
tx.executeSql('SELECT * FROM colours',
[], function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
//INIT YOUR APP HERE IN ORDER TO HAVE ACCESS TO colourArray values
ColourStore = new Ext....
YourApp.init();
},
onError);
});
}, this);