SQlite count query on virtual table always comes out to 1 - javascript

I have a virtual table in sqlite and I'm running queries against it looking for matches of keywords but the count always comes out to 1. The structure is as follows.
var insertStatement2 = "INSERT INTO pagesfts3 (url,content) VALUES (?, ?)";
var createStatement2 = "CREATE VIRTUAL TABLE pagesfts3 USING fts3 (url VARCHAR,content TEXT)";
var selectStatement2 = "SELECT COUNT(*),url FROM pagesfts3 WHERE content MATCH ? GROUP BY url";
try {
var db = openDatabase("search", "1.0", "search engine", 200000);
db.transaction(function(tx) {
//for example use drop table on each load
tx.executeSql(dropStatement, [], null, onError);
tx.executeSql(dropStatement2, [], null, onError);
tx.executeSql(createStatement, [], null, onError);
tx.executeSql(createStatement2, [], null, onError);
});
db.transaction(function(tx) {
});
}
catch (error) {
$('body').prepend('<div class="alert alert-danger">This script requires a SQlite compatible browser<br/> try Safari 4, iOS OS3, Chrome 5, or Opera 10.5</div>');
}
function onError(tx, error) {
alert(error.message);
}
So basically I save a webpage data and its corresponding url. When I go to query the page I run this
var query = $('#query').val().toLowerCase();
var searchResults = $('#queryResult');
searchResults.html('');
db.transaction(function(tx) {
//run static select statment 2 on the virtual table
tx.executeSql(selectStatement2, [query], function(tx, result) {
var dataset = result.rows;
if (dataset.length > 0) {
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
console.debug(item);
var url = item['url'];
var count = item['COUNT(*)'];
var str = '<p>' + url + ' has the word <b>' + query + '</b></p>';
searchResults.append(str);
}
}else{
searchResults.append('no results');
}
});
});
But the column count(*) is always 1 even though I know they keyword is present more than 1 times. I'm not too familiar with virtual tables so maybe I'm missing something.

Related

my sql query logical error and node.js way to work

There is a table named "absentTeachers" in sql with only one column i.e. name.
I want to add a name to the table if and only if it doesn't already exists, Can someone please give me a query for the same.
And another problem is I have a array of names in my client side JS, I wanted to add those names in the same table so mainly I wanted to know about an efficient way to do this. I was trying something like this which is not even working.
NODE JS CODE TO ADD RECORDS :
app.get('/DataATT-:data', function (req, res) { // UPDATE DATA IN ABSENT TEACHER TABLE
var TeacherName = req.params.data.toString();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'tiger',
database: 'test'
});
var query = "INSERT INTO absentTeachers (name) SELECT '" + TeacherName + "' FROM absentTeachers WHERE NOT EXISTS(SELECT * FROM absentTeachers WHERE name='" + TeacherName + "')";
console.log(query);
connection.connect();
connection.query(query, function (err, rows, fields) {
if(err) res.status(500).send(err.toString());
res.send("Added Teacher " + TeacherName + " to absent Teacher Data");
});
connection.end();
}); // use minus to diff. between tableName and data to add
CLIENT SIDE CODE TO SEND XML REQUEST TO SERVER:
(worst thing I've ever tried, also I want to know if it can work this way.)
var Request = [];
var object = [];
// pastValues stand for the teachers' names array I wanted to add from.
for(var i = 0; i < pastValues.length; i++){
var tempRequest = new XMLHttpRequest();
Request.push(tempRequest);
}
for(var i = 0; i < Request.length; i++){
Request[i].onreadystatechange = function () {
if(Request[i].readyState === XMLHttpRequest.DONE){
if(Request[i].status === 200){
console.log('Completed Request ' + i +'.');
}
}
}
}
for(var i = 0; i < pastValues.length; i++){
Request[i].open('GET', 'http://localhost:3000/updateDataATT-' + pastValues[i], true);
Request[i].send(null);
}
Remember I am not a hardcoder programmer or software developer, I am in high school for now.
Thanks in advance :)

Using Cordova-sqlite-storage plugin

I am using Cordova-sqlite plugin in order to select and insert data to database embedded in an Android device. In my case I create the database from the native code and then I am trying to read some data from JavaScript source. But, I think that JavaScript is not reading from the same location as Android do.
This is my JS file :
var db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
var session = this._sessionInfoService.getSessionInfo();
db.transaction(function (tx)
{
var firstName = session.firstName;
var lastName = session.lastName;
var userId = session.id;
tx.executeSql("CREATE TABLE IF NOT EXISTS user (user_id INTEGER, firstname VARCHAR, lastname VARCHAR)");
tx.executeSql('SELECT * FROM user', [], function (tx, results) {
var len = results.rows.length, i;
console.log(len);
for (i = 0; i < len; i++){
var id =results.rows.item(i).user_id;
console.log(results.rows.item(i).user_id );
if(id!=userId){
var dialogTitle = "Another user is already registred for this device";
var dialogText = "Do you want to override it ";
WL.SimpleDialog.show(dialogTitle, dialogText, [ {
text : 'Override',
handler : function(){
db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
db.transaction(function (tx)
{
tx.executeSql("UPDATE user SET user_id =?, firstname=?, lastname=?", [userId,firstName,lastName]);
}
}
}, {
text : 'No',
handler : function(){
db = window.sqlitePlugin.openDatabase({name: 'db',iosDatabaseLocation: 'Library'});
db.transaction(function (tx)
{
tx.executeSql("INSERT INTO user (user_id,firstname, lastname) VALUES(?,?,?)", [userId,firstName,lastName]);
}
}
}
]);
}
else{
}
}
}, null);
}
});
}
and this is my java file in native source
#Override
public void onStart(Intent intent, int startId) {
final SQLiteDatabase db = openOrCreateDatabase("db",
Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS user (user_id INT, firstname VARCHAR, lastname VARCHAR);");
Log.i("e2", "yes");
db.execSQL("INSERT INTO user (user_id,firstname,lastname) VALUES(91,'ess','ess');");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String query = "SELECT * FROM user";
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
int userId=c.getInt(1);
System.out.println("userId"+userId);
Log.i("userId",String.valueOf(userId));
}
}
catch(e){}
}
});
thread.start();
}
When try to create my database and my user table from JavaScript and then do the select from java file I am facing an exception : the table user is unknown and when I select users from the JS I always get an empty list . That's why I think that my code creates two databases with the same name but in two different locations.

better approach to access datatabase and creating models in cross platform apps

for example , i have been using following approach in my cross platform apps to accessing sqlite database as follows
To access database i have made a saperate .js for UserProfile table
function DBUserProfile()
{
this.selectUserName = function(userId, callback)
{
try
{
//Get Data
localDB.transaction(function selectUserProfileData(tx)
{
var objDBDatabaseSchema = new DBDatabaseSchema();
var sqlCommand = 'SELECT username FROM '
+ objDBDatabaseSchema.UserProfileMetaData.USER_PROFILE_TABLE_NAME
+' WHERE engineer_id='
+ '="' + userId + '"';
objDBDatabaseSchema = null;
tx.executeSql(sqlCommand,[],function selectUserNameResult(tx, results)
{
if (results.rows.length > 0 )
{
var userId = results.rows.item(0).username ;
callback(userId);
}
else
{
var userId = "";
callback(userId);
}
}, errorDB);
}, errorDB);
}
catch (e)
{
// TODO: handle exception
console.log("DBUserProfile - selectUserName " + e);
}
};
}
and this is how i use them in a pages
var objDBUserProfile = new DBUserProfile();
objDBUserProfile.selectUserName("3443" , function(id){
//
});
but the above approach is pretty time consuming i have been end up creating lot of models and db files to access tables and lot of new objects , so does anyone has a better approach in jquery to cut down the development time. any suggestions are welcome

Titanium Studio, JavaScript and SQL Error... Cant figure it out

var url = "http://api.reddit.com/";
var dataArray = [];
var working = function(){
var getData = JSON.parse(this.responseText);
var titles = getData.data.children;
for(var i=0, j=titles.length; i<j; i++)
{
var title = titles[i].data.title;
dataArray.push({
title: title,
favorite: 0
});
}
save(dataArray);
}; //working
var save = function(arg){
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', arg.title, arg.favorite);
var rowID = db.lastInsertRowId;
//newRow.id = rowID;
//rows.close();
db.close();
gather();
};
var dataContent = [];
var gather = function(){
var db = Ti.Database.open("newData");
var dbRows = db.execute("SELECT name, favorite FROM redditTitles"); // Returns a Result Set object
while(dbRows.isValidRow()){
dataContent.push({
title: dbRows.fieldByName("name"),
fav: dbRows.fieldByName("favorite")
});
console.log("dataContent: "+ dataContent.title);
dbRows.next();
}
dbRows.close();
db.close();
console.log(dataContent);
userInterAPI();
};
var error = function(){
alert("Please check your network connection and try again.");
};
var client = Ti.Network.createHTTPClient({
onload: working,
onerror: error,
timeout: 5000
});
client.open("GET", url);
client.send();
So Basically me and my instructor have been scratching our heads trying to figure out why the arg will show all of the data but after the data is saved and we go to re console log it out, it will show up as null. Not sure why. Someone please help me!
You are saving just one item (Incorrectly - that's why is undefined). If you want to save everything you have to iterate through whole array.
var save = function(arg) {
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute("BEGIN"); // Transaction
arg.forEach(function(item) {
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', item.title, item.favorite);
//var rowID = db.lastInsertRowId;
});
db.execute("COMMIT");
db.close();
gather();
};
In the function called gather - if you want to see selected title you should use:
console.log(dbRows.fieldByName("name"))
alternatively (This is what you wanted to use):
console.log(dataContent[dataContent.length - 1].title)
instead of
console.log(dataContent.title); // dataContent is an Array.
*Of course you better avoid using dataContent.length in every iteration. That's just an example.

html5sql - Can't seem to connect to my DB

I'm using html5sql.com for doing html5 DB stuff :o)
- Really a great module...
However, I got stuck!
At my index.html/index.js I create my database and tables in it.
try {
html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*1024*1024);
html5sql.process(
[
"CREATE TABLE IF NOT EXISTS Questionnaire (uid INTEGER, json TEXT, hash TEXT);",
"CREATE TABLE IF NOT EXISTS Answers (id INTEGER PRIMARY KEY, visitor_id TEXT, json TEXT);"
],
function(){
console.log("Success Creating Tables");
},
function(error, statement){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Database create failed: "+error.message);
}
And further in the same page I populate one table with data:
jQuery.get(serverHttp+"json.php?exhibitorID="+exhibitorID, function(data){
var html = $(data).map(function() {
return $(this).html();
});
var jsonStr = html[0];
var exhibitorID = html[1];
var hashStr = html[2];
var SQL = "INSERT INTO Questionnaire (uid, json, hash) VALUES ("+exhibitorID+",'"+jsonStr+"','"+hashStr+"')";
try {
html5sql.process(SQL,
function(){
console.log('Inserted 1 row!');
},
function(){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Query failed: "+error);
}
Now, in a different page called questionnaire.html/questionnaire.js I'm trying to retrieve the data I stored in the table Questionnaire.
html5sql.process(
["SELECT * FROM Questionnaire;"],
function(transaction, results, rowsArray){
for(var i = 0; i < rowsArray.length; i++){
var uid = rowsArray[i].uid;
var json = rowsArray[i].json;
var hash = rowsArray[i].hash;
console.log("Retrieved rows: "+uid+" - "+json+" "+hash);
}
console.log("Done selecting data");
},
function(error, statement){
console.error(error.message+" Occured while processing: "+statement);
}
);
What am I doing wrong???
Regards,
Daniel
Solved! Inserted: html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*102‌​4*1024); Before html5sql.process() at questionnaire.js

Categories

Resources