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);
}
});
Related
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);
I am working in cordova. I created one database and table in it. It's work perfectly. But When I run application again database is not exist. It was deleted. I am using sqlite plugin https://github.com/litehelpers/Cordova-sqlite-storage
Please help me. I wasted my lots of time for that didn't get any solution.
My code for create database
define([
'cordova',
'logs'
], function () {
SQLiteDB = function () {
var self = this;
this.dbName = 'AppDb.s3db';
this.db = null;
/*
Populate database
*/
this.openDatabase = function (callback) {
this.db = sqlitePlugin.openDatabase({
name: this.dbName, location: 2, createFromLocation: 1
});
this.db.transaction(
function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS myDB(pax_id integer primary key, user_token text)');
if (typeof callback == 'function') {
callback.call();
}
},
this.dbErrorHandler
);
},
this.addLoginDetail = function (pax_id, user_token, successCallback) {
var that = this;
if (!this.db)
this.openDatabase();
that.db.transaction(
function (tx) {
tx.executeSql("INSERT INTO myDB (pax_id, user_token) VALUES (?,?)", [pax_id, user_token], function (tx, res) {
console.log("Save device config to local database");
Logs.logWrite("Save device config to local database");
if (typeof successCallback == 'function') {
var config_settings = null;
config_settings = JSON.parse(val.CONFIG_SETTINGS);
config_settings.LAST_UPDATE_TIME = lastUpdateTime;
if (!config_settings.APP_TYPE)
config_settings.APP_TYPE = 'D';
successCallback.call(config_settings);
}
});
},
that.dbErrorHandler
)
}
this.getLoginDetail = function (successCallback) {
var that = this;
console.log('call Login detail in local database');
Logs.logWrite('call getEmployee in local database');
if (!this.db)
this.openDatabase();
this.db.transaction(
function (tx) {
tx.executeSql("SELECT pax_id, user_token from myDB;", [],
function (tx, res) {
if (typeof successCallback == 'function') {
var employee = null;
var config_settings = null;
if (res.rows.length > 0) {
config_settings = JSON.parse(res.rows.item(0).config_settings);
console.log("dbLogin =============>> " + JSON.stringify(config_settings));
employee = res.rows.item(0);
}
successCallback.call(config_settings);
}
},
that.dbErrorHandler
)
},
that.dbErrorHandler
);
}
}
return SQLiteDB;
});
Updating your cordova version should resolve the issue.
and keep in mind that WebSQL API is depricated. It is unlikely to ever be supported on platforms that don't currently support it, and it may be removed from platforms that do.
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.
I have multiple sql file in my assets folder and building app on android. I want this sql to import in android app database on by one using jquery. How to do that please help. I have done code for single file but i want it for multiple sql file.
var filePath = 'database/crmaaaa_1.sql';
//alert(filePath);
$.get(filePath, function (response) {
var statements = response.split('\n');
var shortName = "crm1";
var version = '1.0';
var displayName = 'crm1';
var maxSize = 40000000; // bytes
// db = openDatabase(shortName, version, displayName, maxSize);
var db = window.openDatabase(shortName, version, displayName, maxSize);
// db.transaction(populateDB, errorCB);
db.transaction(function (transaction) {
jQuery.each(statements, function (index, value) {
// alert("query"+value);
if (value != '') {
transaction.executeSql(value, [], successHandler, function (e) {
alert("Error executing sql " + value);
});
}
});
});
});
You can create an array of sql files to import:
var sqlFiles = ['file1.sql', 'file2.sql', 'file3.sql'];
$(sqlFiles).each(function() {
$.get(this, function (response) {
// your sql file management
// ...
}
});
This should get you to the goal.
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