how to get last inserted row id in sqlite - javascript

function insertToProject(cast, pName)
{
db.execute('INSERT INTO project (cd, pn) VALUES (?,?)', cast, pName);
var x = last_insert_rowid();
return x;
}
I have been trying this using javascript in titanium appcelerator. Can anybody tell me what I am doing wrong?

For this you can use the lastInsertRowId property of database object.
You can use like:
var x = db.lastInsertRowId;
lastInsertRowId
lastInsertRowId : Number
The identifier of the last populated row
Please check this link for more details : Titanium.Database.DB

You may also do:
db.transaction(function(tx) {
tx.executeSql("INSERT INTO project (cd, pn) VALUES (?,?)", cast,
function(tx, res) {
var id = res.insertId;
});
});
Thus, getting the result of the successful insert and then its property insertId

Related

get values out of array

Hi i'm searching for some help with the below piece of code. I would like to map and put the values in the SQL db. But I can't seem to get the values out of the array ttNieuweSessie.
So with a result that all values are undefined. Does someone have tips on how to get it working?
msg.topic = ttNieuweSessie.map(function(){
return 'INSERT INTO tblSessies (idSessie, BeginTijdms, idApparaat) VALUES ('+idSessie+', '+BeginTijdms+', '+idApparaat+') ';
});
You have to add a parameter to the function you specified as callback for .map() to get acces to the currentValue.
var queries = ttNieuweSessie.map(function(val){
return 'INSERT INTO tblSessies (idSessie, BeginTijdms, idApparaat) VALUES ('+val.idSessie+', '+val.BeginTijdms+', '+val.idApparaat+') ';
});
Then your queries variable contains an array with a query for every element in ttNieuweSessie
msg.topic = ttNieuweSessie.map(function(value){
return 'INSERT INTO tblSessies (idSessie, BeginTijdms, idApparaat) VALUES ('+value.idSessie+', '+value.BeginTijdms+', '+value.idApparaat+') ';
})
You can pass current value to function in map method

Set object properties in loop parse.com

I'm using the Parse.com javascript SDK and I'm trying to set some fields of the object in the loop, but only those fields which I am creating in the loop are not getting saved in parse also it is not giving me any error.
CODE:
var room = new Room();
room.id = params.roomId;
var rate = new Rate();
rate.set('room', room);
for (var i = 0; i < 100; i++) {
rate.set("rate" + i, params.price); // this fields are not getting saved
}
rate.save(null, {
success: function(rate) {
params.success(Response.SaveSuccess);
},
error: function(rate, error) {
console.log('ERROR SAVING RATE: ' + error.message);
params.error(Response.InternalServerError);
}
});
After successful response, I can see only room field in database
The way you are trying to set values in rate object seems a little weird. The first argument of "set" method of Parse.Object accepts only column name enclosed in inverted commas. So following is the only solution of updating an object in Parse Js:
rate.set("rate", params.price);
P.S. You need to elaborate what exactly you want to achieve in your code so that a proper solution can be posted.
Thanks

How to query for ids and properties stored in object

So I'm storing checkbox data in an object that is stored with Parse.com. This is working correctly and is storing the object as follows:
Object {c1: false, c2: false, c3: false}
Where 'c1'=id of the checkbox and false obviously is the boolean value for unchecked.
I'm trying to create a function that queries that object and then rewrites the checkboxes with the properties. Here is my attempt at that:
var Checklist = Parse.Object.extend("Checklist");
//get checkboxes from parse and load them onto screen
function getChecklist()
{
var user = Parse.User.current();
var q = new Parse.Query(Checklist);
q.include("user");
q.equalTo("user", user);
q.descending("createdAt");
q.find({
success: function(results)
{
//this variable will need to change to be associated with the user's checklist
var i=0;
var check = results[i].get("check");
//takes object check and sorts it into order
var sortedKeys = Object.keys(check).sort();
console.log(check[Object.keys(check)[0]]);
//ATTEMPT AT checking the boxes correllated to the sorted keys id for each checkbox
for (var id in check)
{
$("#" + id).attr("checked", sortedKeys[id]);
console.log(check);
}
}, error: function(error){
console.log("Query Error:"+error.message);
}
});
};
getChecklist();
The 'check' is a column of checklist where the object is stored on Parse. As of now, I am unable to set the sortedKeys ('c1''c2''c3'etc.) to the checkboxes and furthermore cannot associate the boolean properties of those keys with the checkstate.
Any advice? Here is a gist with the whole html+script if further information is needed/wanted. https://gist.github.com/ripplep/75627c25ade7c5e57883
P.S. I apologize if the code is formatted inconsistently, as I am fairly new to programming.
EDIT with correct code:
function getChecklist()
{
var user = Parse.User.current();
var q = new Parse.Query(Checklist);
q.include("user");
q.equalTo("user", user);
q.descending("createdAt");
q.first({
success: function(checklist)
{
//this variable will need to change to be associated with the user's checklist
var check = checklist.get("check");
console.log(check);
//takes object check and sorts it into order
//console.log(check[Object.keys(check)[0]]);
//ATTEMPT AT checking the boxes correllated to the sorted keys id for each checkbox
for (var id in check)
{
$("#" + id).attr("checked", check[id]);
console.log(check);
}
}, error: function(error){
console.log("Query Error:"+error.message);
}
});
};
i would advice to simplify it to prevent this troubling code.
given working fiddle example
the main idea is just loop the object using:
var obj = {c1 : false, c2 : true, c3 : false }
for (var id in obj) {
$("#" + id).attr("checked", obj[id]);
}
please see fiddle to complete solution.

sqlite - unable to query web db with WHERE clause

I'm using the WHERE clause while trying to query my sqlite database. I know there is data in the db which I should be able to retrieve based on the conditionals in my query, but I can't seem to get it to work.
When I query without conditionals...
sql = 'select LocationGUID, ID, Fullname FROM tblUser';
I'm able to return all the data from the selected columns. Is this is a quotation issue? I've tried single and double-quotes around the conditional values but the number of rows I return is still 0.
Javascript:
sql = 'select LocationGUID, ID, Fullname FROM tblUser WHERE UserName=\'mike\' AND Password=\'mike123\'';
mydb = getDBConn();
mydb.transaction(function(tx) {tx.executeSql(sql, [], function(tx,results) {
var size = results.rows.length;
console.log(size);
for (var i=0;i<size;i++) {
for (var key in results.rows.item(0)){
var row = results.rows.item(i);
console.log(row[key]);
}
}
SQLite DB
The correct query to find this row would be this:
SELECT ... FROM tblUser WHERE UserName = 'mike ' AND ...
You might want to change the code that stores the data to remove these unwanted spaces.
To fix the database, use something like this:
UPDATE tblUser SET UserName = rtrim(UserName)

SQLite database on phonegap resultset length increase every time

I am developing an application using phonegap and i am using database as sqlite.
I have created a table using following commands:
var dbb;
var shortName = 'Vaccine1';
var version = '2.0';
var displayName = 'vaccine';
var maxSize = 100000;
dbb = window.openDatabase(shortName, version, displayName,maxSize);
and inserted values using this function..
function AddDBvalues()
{
dbb.transaction(function(tx){
//tx.executeSql( 'DROP TABLE IF EXISTS Vaccin',nullHandler,nullHandler);
tx.executeSql( 'CREATE TABLE IF NOT EXISTS Vaccin(Vday INTEGER NOT NULL,VName TEXT NOT NULL, CCountryid INTEGER NOT NULL , Sex TEXT NOT NULL)', [],nullHandler,errorHandler);},errorHandler,successCallBack);
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["0","BCG","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["0","OPV dose 1 of 5","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["1","Hepatites B dose 1 of 2","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["42","DPT dose 1 of 3","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["42","OPV dose 2 of 5","91","both"], nullHandler,errorHandler);});
dbb.transaction(function(transaction) {transaction.executeSql('INSERT INTO Vaccin(Vday,VName,CCountryid,Sex) VALUES (?,?,?,?)',["70","DPT dose 2 of 3","91","both"], nullHandler,errorHandler);});
}
and used this function to get valuse from database..
function ShowValue()
{
var cnn = sessionStorage.getItem('cid');//getting from session
var cn=parseInt(cnn);
alert (cn); //always show correct value
dbb.transaction(
function (transaction) {
transaction.executeSql("SELECT * from Vaccin WHERE CCountryid='"+cn+"';",[], dataHandler, errorHandler);});
function dataHandler(transaction, results){
alert("first method" + results.rows.length);
for (var i=0; i<results.rows.length; i++) {
...... }
}}
i am getting an unexpected error is that the length of resultset increase every time
means if run app first time it show correct value and when i run it again it just show the length of resultset = results.rows.length+results.rows.length means double and so on....every time.
please help me if anybody know what's going wrong.
Is AddDBValues getting called on every run of the app? IF NOT EXISTS has no effect on the insert statements.
Is the database persistent between runs? If so then the data is doubling because not you're dropping the table. In you AddDBvalues() function the DROP ... command is commented out.
//tx.executeSql( 'DROP TABLE IF EXISTS Vaccin',nullHandler,nullHandler);
Unrelated but you also have a possible SQL injection vulnerability. The variable cn should be passed in as a bind variable and not simply added to the SQL as a string.
transaction.executeSql("SELECT * from Vaccin WHERE CCountryid='"+cn+"';",[], dataHandler, errorHandler);});

Categories