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.
Related
I have shopping cart in my android App. I am using Firebase as database. I want to mail cart items as CSV / Excel file as attachment.
First you have to fetch all data from firebase.
Read Data From Firebase database
Then you have to generate csv file from the data.
How to create a .csv on android
After that you can send csv file from its path as an attachment to mail
How to send an email with a file attachment in Android
first install excel4node package in your firebase project, then import this in your index.js
const xl = require('excel4node');
also import these for file handling
const os = require('os');
const path = require('path');
const fs = require('fs');
const tempFilePath = path.join(os.tmpdir(), 'Excel.xlsx');
const storage = admin.storage();
const bucket = storage.bucket();
This is how you return the function should look
exports.writeFireToExcel = functions.https.onCall(async(data, context) => {
// Create a new instance of a Workbook class
const workbook = new xl.Workbook();
// Add Worksheets to the workbook
const worksheet = workbook.addWorksheet('Visa Work List');
const ref = firebaseDb.ref('path');
//firebase functions that return stuff must be done in a transactional way
//start by getting snap
return await ref.once('value').then(snapshot =>{
var style = workbook.createStyle({
font: {
bold : true,
},
});
//write workbook
worksheet.cell(1, 1).string('input').style(style);
//....write the rest of your excel
return
//
}).then(function (){
console.log('workbook filled');
//second part of transation - write the excel file to the temp storage in firebase
//workbook.write doesnt return a promise so ive turned it into a promise function
return new Promise((resolve,reject) =>{
workbook.write(tempFilePath, function (err, stats) {
if (err) {
console.error(err);
reject(err)
}else{
resolve()
}
});
})
}).then(function(){
console.log("File written to: " + tempFilePath);
//read the file and check it exists
return new Promise((resolve,reject) =>{
fs.readFile(tempFilePath, function (err, data) {
if (err) {
reject(err)
}else{
resolve()
}
})
})
}).then(function(){
console.log("writing to bucket");
//write the file to path in firebase storage
var fileName = 'VisaSummaryList.xlsx';
var folderPath = uid + "/excelFile/";
var filePathString = folderPath + fileName;
return bucket.upload(tempFilePath,
{ destination: filePathString}).then(function(){
return filePathString;
})
}).catch(err => {
throw err;
});
});
the function returns a filepath in the firebase storage. In your android app just:
//firebase storage reference, result being whats returned from the firebase function
val fbstore = FirebaseStorage.getInstance().reference.child(result)
fbstore.getFile(myFile)
I have created an app using ionic1 and it is live but some serious issues takes place in sqlite that is some datas are not updated in different tables. I would like to know is there any way to take the sqlite db from the app and save it in external storage using ionic1 and angular js. As well as i would like to know is it possible to again push the sqlite.db from external storage to the app and do the normal process.
You can do it by taking the database file out and make changes in the database and push the database again to the location
To Take the db from applicationstorage to external storage use this command:
function gotoDBBackup () {
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
var PARENT_DIR = 'file://mnt/sdcard/';
var NAME_DB = 'DB.db';
var NEW_NAME_BACKUP = 'KPbackup.db';
window.resolveLocalFileSystemURL(URI_DB + NAME_DB, function (fs) {
window.resolveLocalFileSystemURL(PARENT_DIR, function (directoryEntry) {
fs.copyTo(directoryEntry, NEW_NAME_BACKUP, function () {
$log.log('The database backup was successful.');
alert('Backup ok');
});
});
});
}
To replace db use the command:
function replaceDB () {
/*window.resolveLocalFileSystemURL('file:///data/data/TestpatchKP/databases/DB.db', function (fs) {
var parent = 'file://mnt/sdcard/';
var newName = 'kpupdated.db';
window.resolveLocalFileSystemURL(parent, function (directoryEntry) {
fs.copyTo(directoryEntry, newName, function () {
alert('Backup ok');
}, failFiles);
});
}, failFiles);*/
var DATABASE_DIR = 'file://mnt/sdcard/';
var DB_NAME = 'kpupdated.db';
var NEW_NAME = 'DB.db';
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
window.resolveLocalFileSystemURL(DATABASE_DIR + DB_NAME, function (fs) {
window.resolveLocalFileSystemURL(URI_DB, function (directoryEntry) {
fs.copyTo(directoryEntry, NEW_NAME, function () {
$log.log('Database has been restored successfully');
alert('Database restored successfully');
}, failFiles);
});
}, failFiles);
}
To remove a db :
function removeDB () {
var NEW_NAME = 'DB.db';
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
window.resolveLocalFileSystemURL(URI_DB + NEW_NAME, function (fs) {
fs.remove(success, fail);
$log.log('Db removed successfully');
}, failFiles);
}
To view the database use the tool DB for browser. Hope it might help you.
I am using Ionic Framework. I want to ask for help about how to insert more than 1000 rows at a time and while insertion showing a loading spinner to user so that there wont be any mess in database.
First, I have two services/factories.
Database :
.factory('DB', function ($ionicPopup, $cordovaSQLite, $q, $ionicPlatform, $cordovaNetwork,$ionicLoading) {
var self = this;
self.query = function (query, parameters) {
parameters = parameters || [];
var q = $q.defer();
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, query, parameters)
.then(function (result) {
console.log(result);
q.resolve(result);
}, function (error) {
console.log(error+" .."+error.message);
alert('I found an error' + error.message);
q.reject(error);
});
});
return q.promise;
}
// Proces a result set
self.getAll = function (result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
}
// Proces a single result
self.getById = function (result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
}
return self;
})
Secondly, AsyncService for downloading data from multiple urls
.service('asyncService', function ($http, $q) {
return {
loadDataFromUrls: function (urls) {
alert("I am inside new Service ");
var deferred = $q.defer();
var urlCalls = [];
angular.forEach(urls, function (url) {
urlCalls.push($http.get(url.url));
});
// they may, in fact, all be done, but this
// executes the callbacks in then, once they are
// completely finished.
$q.all(urlCalls)
.then(
function (results) {
deferred.resolve(results)
},
function (errors) {
console.log(errors);
deferred.reject(errors);
},
function (updates) {
console.log(updates);
deferred.update(updates);
});
return deferred.promise;
}
};
})
And the method that firstly, should download the datas and then insert them into their belonged tables.
asyncService.loadDataFromUrls(urLs).then(function (result) {
DB.query("DELETE FROM INV");
// when i have to update the tables, i first delete them and then fill them back again.
$ionicLoading.show({
template : 'Processing into Database. Please Wait...',
timeout : '6000'
});
result.forEach(function (rows) {
console.log(rows.config.url);
var i = 0;
if (rows.config.url == 'http://11.444.222.55:55/mobil_op?op=get_inv') {
rows.data.forEach(function (entry) {
var parameters = [entry.code, entry.name,];
DB.query("INSERT INTO INV (CODE,NAME,......) VALUES(?,?........)",parameters);
})
}
})
}, function (err) {
alert("OOpsss ! : " + err.message);
console.log("error");
}, function (updates) {
alert("updates");
console.log("updates" + updates);
})
How should I work while inserting 4453 elements into array ?
db.executeSql("BEGIN TRANSACTION",{})
.then(( res )=> {
console.log(res);
// DO ALL INSERTION ON THE TABLES
// e.g
// AT LAST
db.executeSql("COMMIT",{})
.then(()=> console.log("COMMIT")
.catch(e => console.log(e));
}).catch(e => console.log(e));
// This process provided me much more faster way . The method above in the question dialog was inserting 4553 items in 3 minutes on Asus Zenphone 1. This method let me insert 10000 items less then 3 minutes.
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.
Below is my example that I have. So far it does the following.
Enter in 3 values to a row
Retrieve all the values from all rows on load
Place all the values from each row and print them to screen that was
retrieved from the above step.
The part that I need help with is trying to find all the values of one row based on a value that exists in that row.
If a row contains the values name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ I would like to get all the data of that row when some one searches for ‘Andrew’
So far if you look at the function ‘searchItems’ you will see that I am trying to find data based on the value of the search input. The problem I am having is all I can get it to do is alert an “undefined” response.
How can I write the function to have it find things like described above
Also one step further. How can i edit the data that is in the row that was found based on the search input? (I have not written that function yet)
html
<!--jquery-2.1.4.js-->
<body>
<input type="text" id="dataGoesHere" />
<input type="text" id="moredataGoesHere" />
<input type="text" id="mostdataGoesHere" />
<button id="clickme">Save</button>
<div id="saved"></div>
<br><br>
<input type="text" id="searchString" />
<button id="search">search</button>
</body>
js
$(document).ready(function() {
myDb = function () {
var name = "test",
version = "1",
db,
testStoreName = "exampleStore",
testIndexName = "testIndexName",
addToTestIndex = false,
init = function () {
var deferred = $.Deferred(),
openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = dbUpgrade;
openRequest.onsuccess = dbOpen;
openRequest.onerror = dbError;
return deferred.promise();
function dbUpgrade(evt) {
//here our db is at evt.target.result here we can adjust stores and indexes
var thisDb = evt.target.result, //the current db we are working with
newStore = thisDb.createObjectStore(testStoreName, {keyPath: "id", autoIncrement: true});
//Using indexes, you can target specific keys, this can be an array!
newStore.createIndex("testIndexKey", "testIndexKey", {unique : false});
console.log("Doing an upgrade");
}
function dbOpen(evt) {
console.log("DB successfully opened");
db = evt.target.result;
deferred.resolve();
getAllItems (function (items) {
var len = items.length;
for (var i = 0; i < len; i += 1) {
console.log(items[i]);
$('#saved').append('<p>'+items[i].item + ' ' + items[i].george + ' ' + items[i].column3 + ' ' + items[i].id + '</p>');
}
});
}
function dbError(error) {
console.log("DB Error");
console.log(error);
deferred.reject(error);
}
},
add = function(item, bob, villa) {
var itemToAdd = {"item" : item, "george" : bob, "column3" : villa},
objStore,
request,
deferred = $.Deferred();
if (!addToTestIndex) {
//here we will add half the entries to the index
//See http://stackoverflow.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes for a better example
addToTestIndex = !addToTestIndex;
itemToAdd.testIndexKey = "This is a test";
}
//first get the object store with the desired access
objStore = db.transaction([testStoreName], "readwrite").objectStore(testStoreName);
//next create the request to add it
request = objStore.add(itemToAdd);
request.onsuccess = function (evt) {
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject(evt);
};
return deferred.promise();
},
get = function (index) {
//Since our store uses an int as a primary key, that is what we are getting
//The cool part is when you start using indexes...
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(parseInt(index));
request.onsuccess = function (evt) {
console.log(evt);
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject("DBError: could not get " + index + " from " + testStoreName);
};
return deferred.promise();
},
getAllItems = function(callback) {
var trans = db.transaction(testStoreName, IDBTransaction.READ_ONLY);
var store = trans.objectStore(testStoreName);
var items = [];
trans.oncomplete = function(evt) {
callback(items);
};
var cursorRequest = store.openCursor();
cursorRequest.onerror = function(error) {
console.log(error);
};
cursorRequest.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
};
},
searchItems = function(searchString) {
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(searchString);
request.onerror = function(event) {
// Handle errors!
alert("error");
};
request.onsuccess = function(event) {
alert('start seach')
// Do something with the request.result!)
alert(event.target.result);
alert('end search')
};
};
return {
init: init,
get: get,
add: add,
getAllItems: getAllItems,
searchItems: searchItems
};
}
var db = new myDb();
db.init().then(function () {
$("#clickme").click(function(evt) {
//add, then we will get the added item from the db
console.log("Adding new item to db");
db.add($('#dataGoesHere').val(), $('#moredataGoesHere').val(), $('#mostdataGoesHere').val())
.then(function (res) {
return db.get(res);
})
.then(function (res) {
$('#saved').append('<p>'+res.item+' '+res.george+' '+res.column3+'</p>');
});
});
$("#search").click(function(evt) {
// search for a specific row
console.log("searching");
db.searchItems($('#searchString').val());
});
})
});
First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.
Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):
var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log("!!!!!");
if (cursor.value != null && cursor.value != undefined) {
resultArr.push(cursor.value);
}
cursor["continue"]();
} else {
console.log("################### " + resultArr);
return successCallBack(resultArr);
}
return;
};