I'm building a project using cordova/phonegap and the Cordova-sqlite-storage plugin:
db = window.sqlitePlugin.openDatabase({name: "products.db",location: 'default'});
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS products (id integer primary key, product_id INTEGER,title text,price text, picture text,quantite INTEGER)');
},errorc, function() {
console.log('products table created');
});
In the console I get "products table created" and everything works great, but when I try to insert anything:
db.transaction(function(tx) {
tx.executeSql('INSERT INTO products (product_id, title, quantite, price, picture) VALUES (?,?,?,?,?)',["1","1","1","1","1"]);
},errorc,function() {
$.magnificPopup.close();
showMsg(msg_product_added);
console.log('product added');
});
... and then try to see if it's there and if there are any results with the field product_id equal 1 (the entry we added above does):
db.transaction(function(tx){
tx.executeSql("SELECT count(product_id) as cnt FROM products WHERE product_id=?",1,function(tx,res){
product_total = res.rows.item(0).cnt;
if(product_total <= 0 ){
alert("the row does not exists");
}else{
alert("the row exist");
}
})
}, errorc);
I get "the row does not exists" every time. So what's wrong in the code? This is my error function that return the errors:
function errorc(error){
console.log('error: ' + error.message)
}
Related
i am writing a code for cordova app to delete all data from Web SQL DB table on function call.
Here is the code
function removeitem(){
db.transaction(function (tx) {
tx.executeSql("DELETE FROM hist", [], function (tx, result) {
toast('Deleted');
}, function (error) {
alert(error.code);
});
}, function (error) {
alert(error);
});
}
But the code doesn't work and always give alert
[Object SQLError]
Other functions for creating table, updating records are working fine but delete query is creating problem. Please help guys to identify the problem.
THANKS
As long as you want to delete all data from table, try below statement:
TRUNCATE TABLE hist;
tx.executeSql("TRUNCATE TABLE hist",[],
function(tx,results){console.log("Successfully Emptied")},
function(tx,error){console.log("Could not Empty")}
);
or
tx.executeSql("DELETE FROM hist",[],
function(tx,results){console.log("Successfully Emptied");},
function(tx,error){console.log("Could not Empty");}
);
One of them must work.
Full code:
var db.transaction(function (tx) {
tx.executeSql("DELETE FROM hist",[],
function(tx,results){
console.error("Successfully Emptied");
},
function(tx,error){
console.error("Error: " + error.message);
}
)
});
I just noticed, it was a silly mistake. I was calling
toast('Deleted');
function which was not yet defined therefore the statement was failing.
Sorry for my bad and thanks for helping.
I am working on a phonegap app, and have so far set-up the database to which I have the insert and delete function's working correctly.
I am now struggling on checking input values with the data in the database, so for example for now I am just simply attempting to check if any rows are returned, and if there is that will mean the user and pass entered are in the database, if no rows are returned then the user and pass is false.
I am not getting any errors from the sql statement (function errorCB), as well I did put an debug alert within the function LoginSuccess and that worked, however after removing the debug alert in the LoginSuccess function, I do not get prompted with any alerts and instead the page just refreshes.
I have removed the delete and insert functions from the code as it's relevant to this issue.
Any help will be much appreciated.
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function createDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mahdi (FirstName text, LastName text, Email text, Password text)');
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
alert("Database Ready");
}
function loginUser()
{
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(loginDB, errorCB, LoginSuccess);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'");
} function LoginSuccess(tx, results) {
if (results.rows.length > 0) {
alert ("User and Pass Found");
}
else
{
alert ("User and Pass incorrect");
}
}
Don't worry, all fixed. See below if you'd like to see what I changed around. Seem's as though it was the missing array [] in the executesql statement and calling the renderList (changed from loginSuccessful) into the exectutesql statementent.
function loginDB(tx)
{
alert("yep yep yep");
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("User and Pass Found");
}
else
{
navigator.notification.alert("User and Pass incorrect");
}
}
I build an mobile app hibrid base with phonegap and jquery mobile. My app has a login system, retrieve data from database in server and insert it to sqlite when login succes, so the app can access to the data even it's offline.
i use plugin from litehelpers. And this my sql connect script in database.js:
document.addEventListener("deviceready", connectDB, false);
var kode = JSON.parse(window.localStorage['konfirmasi']);
//create or open Database
function connectDB(){
db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
db.transaction(populateDB,successCB,errorCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}
//function will be called when an error occurred
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
console.log("Connected to database!");
//db.transaction(queryDB,errorCB);
}
function insertDB(tx){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
};
}
function queryDB(){
db.transaction(insertDB,errorCB,querySuccess);
}
function querySuccess(){
console.log('Insert query success!');
}
function dropDB(){
db.transaction(dropQuery,errorDrop,successDrop);
}
function dropQuery(tx){
tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}
function successDrop(){
console.log('Drop table successful');
}
function errorDrop(err){
console.log('Drop table unsuccessful, Error code: '+err.code);
}
function selectData(err){
db.transaction(selectQuery, errorCB, successQuery)
}
function selectQuery(tx){
tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
// for an insert statement, this property will return the ID of the last inserted row
console.log("Last inserted row ID = " + results.insertId);
}
Then, when user login for the first time and success it will retrieve data from server with json, and i want my app to insert retrieved data to sqlite. So, how to put the query for login success only? After that i want to make it DROP table and clear localStorage when it's logout.
This is my login and logout script (main.js):
$(document).on('pageinit','#login',function(){
$(document).on('click','#submit',function(){
if($('#username').val().length>0&&$('#password').val().length>0){
var un = $('#username').val();
var pw = $('#password').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
data:{ username : un,
password : pw
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(result){
console.log(result);
if(result.status==true){
user.name=result.message;
window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
var kode = JSON.parse(window.localStorage['konfirmasi']);
console.log('Array length: '+kode.length);
queryDB();
console.log('Login berhasil');
$.mobile.changePage("#konfirmasi");
window.localStorage.setItem('uname', un);
window.localStorage.setItem('passwd', pw);
console.log(window.localStorage['uname']);
}else{
alert('Login gagal. Username atau password tidak sesuai');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
$(document).on('pagebeforeshow','#konfirmasi',function(){
$.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});
$(document).off('click').on('click','#logout',function(){
window.localStorage.clear();
dropDB();
$.mobile.changePage("#home");
});
function exitFromApp(){
navigator.app.exitApp();
}
So, am i at the right way for logout script? I didn't know it works or not because i still cannot try it because the login script still error when i try it with insert query.
Can someone help me make it done, please?
Where are u calling this piece of code from?
function insertDB(tx,val){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
};
}
If you are calling it from a transaction, then the "val" parameter will not be passed to the insertDB function directly. You might try the following thing:
val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);
Moreover, make sure that the stements always run within a db.transaction context
Have fun!
I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.
I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference