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?
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 write some simple app for windows 8 Metro UI with javascript. Because natural method from microsoft to use Sqlite with Javascript in Metro UI. I use 'doo' wrapper:
dooWrapper SQLite (github)
I create a method :
function addSomething(name) {
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\a_db.sqlite';
SQLite3JS.openAsync(dbPath).then(function (db) {
return db.runAsync("INSERT INTO STH (nazwa) VALUES (:name)", { name: name }).
done(function () {
console.log('Add sth : ' + name);
db.close();
}, function (error) {
if (db) {
db.close();
}
console.log('ERROR Adding sth' + error.message);
})
});
}
I get error 'database is locked' I read about this error in documentation. But I have one question is other solution to add more rows without create 'insert' function with collections argument something like that : insert (array) ? I just want to use that function n-times without this error. That's possible?
Yes,it possible...i also got this error before....For that you just need to establish the database connection once...i have used this in my app and its working fine.
If there is no need of closing your db then then open database once like..
Add this code to default.js file
var myDatabase; //Global Variable
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\db.sqlite';
//Create Table
SQLite3JS.openAsync(dbPath).then(function(db) {
myDatabase=db;
return db.runAsync('CREATE TABLE Item (name TEXT, price REAL, id INT PRIMARY KEY)');
});
Then you just need to use below code
// For Insert
return myDatabase.runAsync('INSERT INTO Item (name, price, id) VALUES ("'+ array[i].name+'", "48484", 1);
For array
var dbPromises = [];
var testArray = [];
//only for test purpose
//You can pass your array here directly
for (var a = 0; a < 300; a++) {
var obj = {
name: "Mango"+a,
price: 100+a,
id: a
};
testArray.push(obj);
}
for (var i = 0; i < testArray.length; i++) {
var query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + ')';
dbPromises.push(globalDatabase.allAsync(query));
}
WinJS.Promise.join(dbPromises).then(function () {
debugger;
}, function(err) {
debugger;
});
Above code is used only for less array size...bcz its taking too much time for insertion...
For fasst execution you should replace just below code
for (var i = 0; i < testArray.length; i++) {
var val = '("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + '),';
query = query + val;
if ((i + 1) % 300 == 0 || (i + 1) == testArray.length) {
query = query.replace(/,$/, "");
dbPromises.push(globalDatabase.allAsync(query));
query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ';
}
}
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');
};
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});
}
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);