Phonegap SQLite error processing 5: No. of '?' doesn't match - android

I am not getting what's happening with my codes. I don't know why I am getting No. of '?'s in statement string doesn't match arguement count while I am not using '?' to insert values. Here is my code:
db = window.openDatabase("myDB", "1.0", "Test DB", 2000000);
db.transaction(populateDB, errorCB, successCB);
$.ajax({
type: 'POST',
url: "MY_SERVER_URL",
data: {"email": email, "password": password},
success: function (response) {
db.transaction(function (tx) { saveDetailsInDB(tx, JSON.stringify(response)) } ,errorCB , successInsertion);
},
error: function (errorMessage) {
window.alert("Something went wrong!");
}
});
}
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS UserDetailsInJSONform');
tx.executeSql('CREATE TABLE IF NOT EXISTS UserDetailsInJSONform (ID INTEGER, JSONdetails TEXT)');
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")');
}
function saveDetailsInDB(tx, response){
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
}
function done(tx) {
alert("success ");
tx.executeSql('SELECT * FROM UserDetailsInJSONform', [], querySuccess, errorCB);
}
// Transaction error callback
function errorCB(err) {
alert("Error processing SQL: "+err.code+" "+err.message);
}
// Transaction success callback
function successCB() {
alert("Positive successCB");
}
function successInsertion() {
alert("Positive successInsertion");
}
function querySuccess(tx,results){
var len = results.rows.length;
alert("Row no. "+len);
for (var i=0; i<len; i++){
alert(results.rows.item(i).ID);
alert(results.rows.item(i).JSONdetails );
}
}
I am beginner in Phonegap. I tried to save my returned data from server in local SQLite DB. But I don't know why I am getting unknown errors. Please Help me !!

2nd argument in tx.executeSql expects values between brackets.
tx.executeSql(sqlToExecuteForTx,bracketValuesForTx,success,error);
In your code:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
It has 'done' as second value which refers to a function in your code. I would recommand to use:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (?,?)',[1,"asd"],done,errorCB);

Related

WebSQL PhoneGap is not returning insertId?

I am using PhoneGap and WebSql. When i am trying it on browser everything is fine.SQLResultSet object has 3 property which are rows,insertId and rowsAffected.
But When i generate and Apk and trying a mobile device, SQLResultSet object has two property rows and rowsAffected.It is getting rowsAffected 0 on mobile device however it is getting 1 in browser on pc.On mobile device 'insertID' getting undefined.
db.transaction(function (t) {
t.executeSql("INSERT INTO TEST (Testname) VALUES (?)", ["test"], function (t, rresult) {
alert(JSON.stringify(rresult));
}, function (t, error) {
alert(error)
})
}, function (error) {
alert("error" + error);
},
function (success) {
alert("success" + success);
})
thanks for help.
The table creation is below.
tx.executeSql("CREATE TABLE IF NOT EXISTS TESTT (Id INTEGER PRIMARY KEY,Testname text)", [],
function (tx, results) { console.log("Successfully created") },
function (tx, error) { console.log("Could not created") }

How to access local variable outside of a function

Here, i am not sure why error function is not working if the C_id comming from server is incorrect. i am getting C_id from server database and passing that C_id to other server in ajax request.
$.ajax
({
url: "http://proserve.ekspeservices.com/client.php",
type: "GET",
datatype: "json",
data: {type: 'login', id: C_id},// getting C_id from server, but here if C_id is incorrect error function is not working
ContentType: "application/json",
error: function()
{
navigator.notification.alert('inCorrect Key');
},
success: function(res)
{
var simpleJson = JSON.parse(res);
myDB.transaction(function (txe1)
{
for (var i = 0; i < simpleJson.User.length; i++)
{
var Cli_id= simpleJson.User[i].id;
myDB.transaction(function (txe)
{
txe.executeSql('CREATE TABLE Client_data(Mobile integer , C_id integer, U_id integer , name text , ip integer )');
});
myDB.transaction(function (txe1)
{
var data_ins = 'INSERT INTO Client_data (Mobile,C_id,U_id) VALUES (?,?,?)';
txe1.executeSql(data_ins, [p,C_id,U_id]
,function(tx, result)
{
navigator.notification.alert('Inserted' , onSignup, 'Info', 'ok');
},
function(error)
{
navigator.notification.alert('Already Registered');
});
});
}
});
}
});
First of i must tell,you are trying to access the variable in your case its client_id whose scope is within that ftr() only.
So you need to define it globally to access it, also you need to define it as an array as you are getting multiple values at a time so you need to push in that.
Your code will be some what like this.
Also you need to call the ab() function after ftr() is finished executing as ab() output is dependent on ftr() result.So, you can go with Jquery deferred or simply call ab() within ftr() as below
var client_id = [];
function ftr()
{
myDB.transaction(function(transaction)
{
transaction.executeSql('SELECT * FROM User_data', [], function (tx, results)
{
var len = results.rows.length;
for (var i=0; i<len; i++)
{
var emp = results.rows.item(i);
client_id.push({
id: emp.C_id,
});
}
}, null);
});
ab();
}
function ab(){
console.log(client_id);
}
function onDeviceReady()
{
myDB = window.sqlitePlugin.openDatabase({name: "mydb.db", location: 'default'});
ftr();
}
Let me know if you have any queries.
Make public that variable outside of the function simple
like this
public yourVariable;
You can also try defining the variable OUTSIDE of the function, and then pass it as a parameter to the function.
This way it can be assigned a value and be used elsewhere.

PhoneGap SQLite error? Uncaught TypeError: Object #<Object> has no method 'exec'

I m developing Android application. I'm integrating the sqlite into my application https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The below error is coming
Uncaught TypeError: Object # has no method 'exec'
while using the following code
window.sqlitePlugin.openDatabase({name: "DB"});
You need to ensure you have waited for Cordova to load prior to opening a database.
As per the README.md from the project:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
// ...
}
https://github.com/xuexueMaGicK/Gift-App
see this link js file is available here database connection are there
window.addEventListener("DOMContentLoaded", init);
function init() {
pageshow = document.createEvent("Event");
pageshow.initEvent("pageshow", true, true);
tap = document.createEvent("Event");
tap.initEvent("tap", true, true);
pages = document.querySelectorAll('[data-role="page"]');
numPages = pages.length;
links = document.querySelectorAll('[data-role="link"]');
numLinks = links.length;
//checkDB();
document.addEventListener("deviceready", checkDB, false);
}
/*******************************
General Interactions
*******************************/
function checkDB() {
navigator.splashscreen.hide();
database = openDatabase('data', '', 'data', 1024 * 1024);
if (database.version === '') {
database.changeVersion('', '1.0', createDB, function (tx, err) {
console.log(err.message);
}, function (tx, rs) {
console.log("Increment transaction success.");
});
addNavHandlers();
} else {
addNavHandlers();
}
}
function createDB(db)
{
/*******Create Table Gifts********/
db.executeSql('CREATE TABLE "gifts" ("gift_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_id" INTEGER, "occasion_id" INTEGER, "gift_idea" VARCHAR(45))', [], function (tx, rs) {
console.log("Table gifts created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Names********/
db.executeSql('CREATE TABLE "names" ("name_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table names created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Occasions********/
db.executeSql('CREATE TABLE "occasions" ("occasion_id" INTEGER PRIMARY KEY AUTOINCREMENT, "occasion_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table occasions created");
}, function (tx, err) {
console.log(err.message);
});
}
In Manifest.xml u have to add plugins related to the SQLite.Then it will work.

Phonegap Passing Argument on Query function. Storage API

I'm working an android application that is wrapped using phonegap and I'm using its Storage API. How can I pass an argument on my Sqlite Query to get a specific row? Thanks in advance. Below is my script. Can you provide me an example? Thanks
$(document).ready(function() {
code = 1;
var db = window.openDatabase("DEMO", "1.0", "DEMOX", 20000000 ); // 20MB in quuota storage size
db.transaction(function(){ queryDB(code) }, errorCB, querySuccess);
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 (!resultSet.rowsAffected) {
alert('No rows affected!');
return false;
}
}
function queryDB(tx, code) {
tx.executeSql('SELECT * FROM table WHERE code = ?', [code], querySuccess, errorCB);
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
});
My solution : hope this will help others.
$(document).ready(function() {
code = 1;
var db = window.openDatabase("DEMO", "1.0", "DEMOX", 20000000 ); // 20MB in quuota storage size
db.transaction(queryDB, errorCB, querySuccess);
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 (!resultSet.rowsAffected) {
alert('No rows affected!');
return false;
}
}
function queryDB(tx) {
var sql = 'SELECT * FROM table WHERE code = :code';
tx.executeSql(sql, [code], querySuccess, errorCB);
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
});

phonegap $.ajax()

anyone know how to store the jsonp data from server in phonegap local database?
the code below can help to connect the phonegap android app to the server, but how to store the data in the phonegap local database?
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
output.text('successful');
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
db = window.openDatabase("SQL", 3, "PhoneGap Demo", 200000);
db.transaction(ajex_call, errorCB);
function ajex_call(tx) {
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//item.obj
tx.executeSql("INSERT OR REPLACE INTO table-name(table-fields) values(?,?,..)", [array-data])
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
More information for local database http://docs.phonegap.com/en/2.2.0/cordova_storage_storage.md.html
Try like this hope this will work:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("SQL", 3, "PhoneGap Demo", 200000);
db.transaction(ajex_call, success, errorCB);
}
function ajex_call(tx) {
tx.executeSql('DROP TABLE IF EXISTS table_name');
tx.executeSql('CREATE TABLE IF NOT EXISTS table_name (fields_required_for_table)');
$.ajax({ url: 'http://172.18.75.156/deals.php', dataType: 'jsonp', jsonp: 'jsoncallback', timeout: 5000, success: function(data, status){
$.each(data, function(i,item){
tx.executeSql("INSERT OR REPLACE INTO table-name(table-fields) values(?,?,..)")
});
}, error: function(){
output.text('There was an error loading the data.');
}
});
}
function success(){
console.log('Success');
}
function error(){
console.log('error');
}
Check out HTML5's local storage.
PhoneGap's docs for it here:
I made a basic database controller class for this kind of thing a long time ago, managed to find it, hopefully it'll give you an idea.
Once you place the DataBaseCtrl code somewhere you'll be able to use it like this:
var myDatabase = DataBaseCtrl();
myDatabase.initWithConfig("DBShortName", "1.0", "MyDbName", 10000);
myDataBase.executeSql("SQL commands here...");
In your case, depending on how your data looks like you would set up your tables
myDataBase.executeSql("CREATE TABLE IF NOT EXISTS LOGS (id unique, log)");
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES (1, 'foobar')");
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES (2, 'logmsg')");
And maybe then use a loop to get all your data in:
for (i = 0; i < data.length; i += 1) {
myDataBase.executeSql("INSERT INTO LOGS (id, log) VALUES ("+i+", "+data[i]+")");
}
Here's the rest of the methods
myDataBase.init(); // uses set/default config
myDataBase.initWithConfig(shortName, version, displayName, maxSize);
myDataBase.executeSql(SqlCmmndString);
myDataBase.executeSqlWithCallBack(SqlCmmndString,SuccessCallbackfunction); // how you get data out
myDataBase.setInitConfig(shortName, version, displayName, maxSize);
This is the class code:
var DataBaseCtrl = function () {
if (!(this instanceof DataBaseCtrl)) {
return new DataBaseCtrl();
}
// Transaction error callback
function errorCB(tx, err) {
console.log("Error processing SQL: " + tx + tx.code + tx.message);
}
function successCB(tx, err) {
}
return {
_DB: null,
_config: {
// Default configuration
_shortName: "DefaultDataBaseName",
_version: "1.0",
_displayName: "DisplayName",
_maxSize: 65535 // in MBs
},
/* Initializer */
init: function () {
if (!window.openDatabase) {
alert("Databases are not supported on this device. \n\n ");
return false;
}
var cfg = {
shrt: this._config._shortName,
vers: this._config._version,
disp: this._config._displayName,
mxSz: this._config._maxSize
};
// Initialize the DataBase.
this._DB = window.openDatabase(cfg.shrt, cfg.vers, cfg.disp, cfg.mxSz);
},
/* Initialize with custom config */
initWithConfig: function (shortName, version, displayName, maxSize) {
this.setInitConfig(shortName, version, displayName, maxSize);
this.init();
},
/* Execute SQL command */
executeSql: function (SqlCmmnd) {
this._DB.transaction(function (tx) {
console.log("Executing SQL... " + SqlCmmnd.substring(0, 100));
tx.executeSql(SqlCmmnd);
}, errorCB, successCB);
},
/* Execute SQL with success callback */
executeSqlWithCallBack: function (SqlCmmnd, SuccessCallback) {
this._DB.transaction(function (tx) {
console.log("Executing SQL... " + SqlCmmnd.substring(0, 100));
tx.executeSql(SqlCmmnd, [], SuccessCallback);
}, errorCB, successCB);
},
/* Sets init config (call before initializing) */
setInitConfig: function (shortName, version, displayName, maxSize) {
console.log("Setting DB Config: " + displayName);
this._config = {
_shortName: shortName,
_version: version,
_displayName: displayName,
_maxSize: maxSize
};
}
};
};
Use an array to store the data from the JSON import. Then save the array to local storage.
$.ajax({
url: 'http://172.18.75.156/deals.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
var ArrayName = [];
$.each(data, function(i,item){
output.text('successful');
ArrayName[i] = item;
});
localStorage.setItem("jsontable",ArrayName);
},
error: function(){
output.text('There was an error loading the data.');
}
});
Then you can call that array using localStorage.GetItem("jsontable");
Then the user will be able to use the imported json table array without having to reimport.
I would suggest you to convert the object to string then save it in the localStorage.
To retrieve data, get the string from localStorage and convert it into JSON object
HTML5 localStorage

Categories

Resources