SQLite database on phonegap resultset length increase every time - javascript
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);});
Related
Query Sql Server able to delete the last row of the table
I would like to expose you my problem: practically, through an AJAX function I call a server-side function, which should execute a query. This query, based on the data provided, deletes the last row of the table where the data in question is present. In the server side function everything works except the query, which instead of deleting the last row, deletes all the rows. Can anyone tell me the exact query? public static void Contr_Dati(string provin) { string queryString = "DELETE FROM Prov_inser WHERE (SELECT MAX (Province_Inserite) FROM Prov_inser) = #Prov"; using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["coso"].ConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(queryString, connection)) { SqlParameter parameter = new SqlParameter("Prov", provin); command.Parameters.Add(parameter); command.ExecuteNonQuery(); connection.Close(); } } }
If #Prov is the Max(key) of the table, your query DELETE FROM Prov_inser WHERE (SELECT MAX (Province_Inserite) FROM Prov_inser) = #Prov is equal to DELETE FROM Prov_inser WHERE 1 = 1 which will delete all rows in the table =================================================================== So you have to change it to DELETE FROM Prov_inser WHERE Province_Inserite = #Prov or without parameter DELETE FROM Prov_inser WHERE Province_Inserite = (SELECT MAX(Province_Inserite) FROM Prov_inser) If #Prov isn't a key, you have to add a key or a timestamp audit field (i.g. Created_Time) to identify the last inserted row of the table.
The solution that comes closest to the problem is: 'DELETE FROM Prov_inser WHERE Province_Inserite = Prov'. However #prov is not a key, but rather an input parameter. Prov_Inser is the name of the table and Province_Inserite is not the key.
How to fetch all the batches for a query at one go using stored proc in azure SQL db?
I am trying to check if there are duplicates in a collection. New to stored procedures and azure database, so for now am trying to count distinct entries. If count distinct (column name) = count (column name), there are no duplicates, so I am trying to write a stored procedure for that. But azure retrieves 100 docs at a time only. I need the count over all the batches available. I was able to get the count of distinct entries, but it shows the count for the first batch retrieved - which is 100. I need the count over all the batches. function sample(prefix) { var collection = getContext().getCollection(); var isAccepted = collection.queryDocuments( collection.getSelfLink(), 'SELECT DISTINCT VALUE r.column FROM root r', function (err, feed, options) { if (err) throw err; if (!feed || !feed.length) { var response = getContext().getResponse(); response.setBody('no docs found'); } else { var response = getContext().getResponse(); response.setBody(JSON.stringify(feed.length)); } }); if (!isAccepted) throw new Error('The query was not accepted by the server.'); } I expect the output to count the distinct entries in the collection. It should be 103, but the actual is 100 which is the number retrieved by azure at one go.
The default value of FeedOptions pageSize property for queryDocuments is 100, which might be the cause of the issue. Please try to set the value to -1. The following stored procedure works fine on my side, please refer to it. function getall(){ var context = getContext(); var response = context.getResponse(); var collection = context.getCollection(); var collectionLink = collection.getSelfLink(); var filterQuery = 'SELECT * FROM c'; collection.queryDocuments(collectionLink, filterQuery, {pageSize:-1 }, function(err, documents) { response.setBody(response.getBody() + JSON.stringify(documents)); } ); } Hope it helps.
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)
Display data from sqlite DB with AngularJS
I like to collect data from an android app and store them into sqlite DB - no problem so far. But now I want to list these data using AngularJS, ng-repeat command. I take the data from the DB via db.transaction(function(tx) tx.execSql...) but now how to format the data rows so that ng-repeat can read them ? I tried an array of objects, I tried building a JSON string - both not working, I got a ngRepeat error. var app = angular.module('demo',[]); app.controller("MainController", function($scope){ // gets the tasks from the DB as json object db.transaction(function(tx){ tx.executeSql("SELECT task,task_detail,task_date FROM task", [], function(tx, rs){ var rows = rs.rows; if (rows.length>0) { var json_arr = []; for(var i = 0; i < rows.length; i++) { var row = rows.item(i); var obj = {task: row.task,detail:row.task_detail,datum:row.task_date}; json_arr.push(obj); } } var json_str = JSON.stringify(json_arr); alert("json_str: "+ json_str); // WORKING ! sessionStorage.tasks = json_arr; // to get result out of db.transaction... }) }); // end db.transaction $scope.tasks = sessionStorage.tasks; -> when i display {{tasks}} it appears as: [object,object] and ng-repeat doesnt work Otherwise if i use the stringified json, it displays correctly in {{tasks}} but ng-repeat causes again error. Another real "dirty" way to get the result of the query into $scope is the sessionStorage thing - I dont like it this way but I cant see another possibility to set the $scope variable to the JSON (or whatever) result of the DB query. Maybe someone has a better idea ? ;) Any ideas ? Thanks a lot, Chris
how to get last inserted row id in sqlite
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