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');
};
Related
I am trying to get some results from the database mysql. I am calling a method to insert into database and another one to read what I inserted before.
I am doing this because node.js not working synchronous. This is my code:
exports.list = function(req, res){
var moduleRows;
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM questions WHERE module_id = ?',[X],function(err,rows)
{
for(var i = 0;i < rows.length;i++){
moduleRows = rows[i];
GetResults(moduleRows);
}
});
var GetResults = function(moduleRows) {
var RightAnswer = 0;
var WrongAnswer1 = 0;
var query = connection.query("SELECT * FROM studentsanswers WHERE Question = '"+moduleRows.question+"' ",function(err,rows2)
{
for(var ii = 0;ii < rows2.length;ii++){
if (rows2[ii].Answer == moduleRows.RightAnswer){
RightAnswer++;
}
else if (rows2[ii].Answer == moduleRows.WrongAnswer1){
WrongAnswer1++;
}
}
var Data = {
question: moduleRows.question,
RightAnswer: moduleRows.RightAnswer,
WrongAnswer1: moduleRows.WrongAnswer1,
NumberOfRightAnswer: RightAnswer,
NumberOfWrongAnswer1 : WrongAnswer1
};
insertResults(Data);
return;
});
}
var insertResults = function(Data) {
var query = connection.query("INSERT INTO statistics set ? ",Data, function(err, rows)
{
PrintResults();
return;
});
}
var PrintResults = function() {
var query = connection.query("SELECT * FROM statistics" ,function(err,rows)
{
res.render('StatisticsByModules',{page_title:"Questions - Node.js",data:rows});
return;
});
}
});
};
I am getting the errors:
Error: Can't set headers after they are sent.
TypeError: req.next is not a function
In following code, you call GetResults(moduleRows) few times which calls PrintResults Few times, In your PrintResults Method you are sending res.render few time which you cannot do for a single request. First, you will have to make your data list then call req.render once with queried data.
var query = connection.query('SELECT * FROM questions WHERE module_id = ?', [X], function (err, rows) {
for (var i = 0; i < rows.length; i++) { // <== HERE
moduleRows = rows[i];
GetResults(moduleRows);
}
});
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 ';
}
}
Resources:
http://docs.phonegap.com/en/2.9.0/cordova_storage_storage.md.html#database_version
Device/Framework Info:
Nexus 4 - Android 4.2.2
Phonegap 2.9.0
Also using the bootstrap library for UI
I have followed the PhoneGap tutorial for version 2.9 on creating, and managing a database. So far I have found little to no places where people are talking about the specific error 23 when trying to write to a database.
I get this error after trying to write to a database after the insertBtn's click function, which executes the insertTemplate function.
The same thing happens when trying to delete a row when the deleteBtn event is fired, which executes the deleteTemplate function.
Any recommendations?
Controller File:
var databaseName = "blackbriar";
var version = 1;
var displayName = "lctv";
var size = 2097152; // two megabytes
var db = null;
$(document).ready(function(event){
// Gets shell for database
db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDb, errorCb, successCb);
db.transaction(loadTemplates, errorCb, successCb);
$('#insertBtn').click(function(event){
db.transaction(insertTemplate, errorCb, successCb);
});
$('#back').click(function(event){
$('#templates').show();
$('#templateEdit').hide();
$('#back').hide();
});
$('#deleteBtn').click(function(event){
db.transaction(deleteTemplate, errorCb, successCb);
$('#back').click();
});
});
$(document).on('click', '.pill', function(event){
// If window width is greater than 480px, isMobile variable is false
var isMobile = $(window).width() > 480 ? false : true;
$('#currentId').text($(this).attr('tempid'));
db.transaction(getTemplateById, errorCb, successCb);
if($('#currentId').text() == "-1"){
$('#insertBtn').show();
$('#saveBtn').hide();
$('#deleteBtn').hide();
$('#clearBtn').show();
} else {
$('#insertBtn').hide();
$('#saveBtn').show();
$('#deleteBtn').show();
$('#clearBtn').hide();
}
// Checks if pill is active for UI changes
if($(this).hasClass('active')){
$(this).removeClass('active');
if(!isMobile){$(this).find('.temp').attr('style', 'color: black;');}
} else {
$('.pill').removeClass('active');
$('.pill').find('.temp').attr('style', 'color: black;');
$(this).addClass('active');
if(!isMobile){$(this).find('.temp').attr('style', 'color: white;');}
}
if(isMobile) {
$('#templates').hide();
$('#templateEdit').show();
$('#back').show();
}
});
My function file:
function getShell(databaseName, version, displayName, size) {
return window.openDatabase(databaseName, version, displayName, size);
}
function populateDb(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS templates (id INTEGER PRIMARY KEY AUTOINCREMENT, templateName, description, campus, account, department, programName, projectId, taskId)');
}
function errorCb(error) {
alert("Error processing SQL: "+error.code);
}
function successCb() {
alert("Success!");
}
function insertTemplate(tx) {
var templateName = $('#templateName').val();
var description = $('#descriptionField').val();
var campus = $('#campusField').val();
var account = $('#accountField').val();
var department = $('#departmentField').val();
var programName = $('#programNameField').val();
var projectId = $('#projectIdField').val();
var taskId = $('#taskIdField').val();
tx.executeSql('INSERT INTO templates (templateName, description, campus, account, department, programName, projectId, taskId) VALUES ('
+'"'+templateName+'"'+', '
+'"'+description+'"'+', '
+'"'+campus+'"'+', '
+'"'+account+'"'+', '
+'"'+department+'"'+', '
+'"'+programName+'"'+', '
+'"'+projectId+'"'+', '
+'"'+taskId+'"'
+')');
}
function loadTemplates(tx) {
tx.executeSql('SELECT * from templates', [], templatesSuccess, errorCb);
}
function templatesSuccess(tx, results) {
var length = results.rows.length;
$('#templateUl').html('');
$('#templateUl').append('<li class="templi"><a class="pill" tempid="-1"><text class="temp"><i style="color: green;" class="icon-plus"></i> Create</text></a></li>');
for(var i = 0; i < length; i++) {
$('#templateUl').append('<li class="templi"><a class="pill" tempid="'+results.rows.item(i).id+'"><text class="temp">'+results.rows.item(i).templateName+'</text></a></li>');
}
}
function getTemplateById(tx) {
var currentId = $('#currentId').text();
tx.executeSql('SELECT * FROM templates WHERE id = '+currentId, [], loadTemplateSuccess, errorCb);
}
function loadTemplateSuccess(tx, results) {
if(results.rows.length > 0){
var template = results.rows.item(0);
var templateName = $('#templateName').val(template.templateName);
var description = $('#descriptionField').val(template.description);
var campus = $('#campusField').val(template.campus);
var account = $('#accountField').val(template.account);
var department = $('#departmentField').val(template.department);
var programName = $('#programNameField').val(template.programName);
var projectId = $('#projectIdField').val(template.projectId);
var taskId = $('#taskIdField').val(template.taskId);
} else {
var templateName = $('#templateName').val('');
var description = $('#descriptionField').val('');
var campus = $('#campusField').val('');
var account = $('#accountField').val('');
var department = $('#departmentField').val('');
var programName = $('#programNameField').val('');
var projectId = $('#projectIdField').val('');
var taskId = $('#taskIdField').val('');
}
}
function deleteTemplate(tx) {
var currentId = $('#currentId').text();
alert(currentId);
tx.executeSql('DELETE FROM templates', [], templatesSuccess, errorCb);
alert("Authorize!!!");
}
Just came into this, i had to uninstall the app and re made it (Also changed the version but i dont think that did it).
Followed this so i uninstall the app everytime i debug. This can be annoying if you have to insert items each time, but atleast solved it.
I was using SQLite in html5 and it worked fine. But the thing was the rows which I was displaying in the page itself were not looking that good. I used innerhtml for displaying the rows as inserted by the user.
Here is the script
function showRecords() {
results.innerHTML = '';
// This function needs a single argument, which is a function that takes
// care of actually executing the query
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
dataset = result.rows;
for ( var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
results.innerHTML += '<li>' + item['lastName'] + ' , '
+ item['firstName']
+ ' <a href="#" onclick="loadRecord(' + i
+ ')">edit</a> '
+ '<a href="#" onclick="deleteRecord(' + item['id']
+ ')">delete</a></li>';
}
});
});
}
/**
* Loads the record back to the form for updation
*
* #param i
*/
function loadRecord(i) {
var item = dataset.item(i);
firstName.value = item['firstName'];
lastName.value = item['lastName'];
phone.value = item['phone'];
id.value = item['id'];
}
/**
* Delete a particular row from the database table with the specified Id
*
* #param id
*/
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql(deleteStatement, [ id ], showRecords, onError);
});
resetForm();
}
So in the code showRecords() method, I have hard coded the data to be displayed. What I want is, that data should be displayed in proper tabular format. I know I have to create elements in JavaScript for dynamic table generation but I am unable to do so and also to display the contents inside table.
Everytime user fills up the form and clicks insert button, insert statement gets executed and then showRecords() method is invoked. I am not able to figure out the proper soluton.
For a pure JavaScript solution, I think this (untested) will work:
function loadRecord(i) {
var item = dataset.item(i);
firstName.value = item.firstName;
lastName.value = item.lastName;
phone.value = item.phone;
id.value = item.id;
}
function showRecords() {
results.innerHTML = '';
// This function needs a single argument, which is a function that takes
// care of actually executing the query
db.transaction(function (tx) {
var i = 0,
table = document.createElement('table'),
tbody = document.createElement('tbody');
tx.executeSql(selectAllStatement, [], function (tx, result) {
var tr = {},
tdName = {},
tdEdit = {},
tdDel = {},
span = {},
aEdit = {},
aDel = {};
dataset = result.rows;
for (i = 0, item = null; i < dataset.length; i += 1) {
//create new table elements
tr = document.createElement('tr');
tdName = document.createElement('td');
tdEdit = document.createElement('td');
tdDel = document.createElement('td');
aEdit = document.createElement('a');
aDel = document.createElement('a');
//grab dataset row
item = dataset.item(i);
//set the name
tdName.innerText = item.lastName + ' , ' + item.firstName;
//create the edit link
aEdit.href = '#';
aEdit.onclick = loadRecord(i);
aEdit.innerText = ' edit ';
tdEdit.appendChild(aEdit);
//create the delete link
aDel.href = '#';
aDel.onclick = deleteRecord(item.id);
aDel.innerText = ' delete ';
tdDel.appendChild(aDel);
//append to row
tr.appendChild(tdName);
tr.appendChild(tdEdit);
tr.appendChild(tdDel);
//append to body
tbody.appendChild(tr);
}
});
table.appendChild(tbody);
results.innerHTML = table.outerHTML;
});
}
/**
* Delete a particular row from the database table with the specified Id
*
* #param id
*/
function deleteRecord(id) {
db.transaction(function (tx) {
tx.executeSql(deleteStatement, [id], showRecords, onError);
});
resetForm();
}
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);