HTML5 WebSQL queries - sql

Hello I jsut wondering if its posibble to have a query on web sql cause im using a phonegap for phone development and i have an error on this code
tx.executeSql("SELECT * FROM DEMO WHERE log=(\"?\")", [_searchtext], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status2').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status2').innerHTML += msg;
}
}, null);
and I can't have any result but on SELECT * FROM DEMO i have a lot of result.

all I am doing is to get all data and put on the loop and condition the data to the searchtext. but i love to make it on the websql. thanks.

Related

SPARQL endpoint exception in Jena: Endpoint returned Content-Type: text/html which is not recognized for SELECT queries

It looks like there is a query length or complexity limit on dbpedia.org/sparql. This code fails:
String part = "{<http://dbpedia.org/resource/Marcus_Garvey__Sound__1>?a?v}";
String query = "SELECT DISTINCT ?a?v WHERE {" + part;
for (int i = 1; i <= 14; i++) {
query += "UNION " + part;
}
query += "}";
ResultSet resultSet =
QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query).execSelect();
while (resultSet.hasNext()) {
QuerySolution qs = resultSet.next();
qs.varNames().forEachRemaining(name -> System.out.println(name + "\t" + qs.get(name)));
}
with the exception:
Exception in thread "main" org.apache.jena.query.QueryException: Endpoint returned Content-Type: text/html which is not recognized for SELECT queries
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execResultSetInner(QueryEngineHTTP.java:378)
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execSelect(QueryEngineHTTP.java:346)
If I change the max i value from 14 to 13, it works fine. If I run the same query using the browser UI, it works fine as well. Any ideas?!

escape underscore in Web Sql

I am developing mobile application in which I have used WebSql as local database. Now I am creating a search functionality where I want to escape "_" when the user will search the records. I tried using the MS-SQL approach by passing it in square bracket "[ _ ]"
Below are my code example
if ($.trim($('#txtPolicy').val()).length > 0) {
policy = $.trim($('#txtPolicy').val());
if (policy.indexOf("_") >= 0)
policy = policy.replace(/_/g, "[_]");
query += " (";
var arrploicy = policy.split(',');
for (var j = 0; j < arrploicy.length; j++) {
query += " policy like ? or ";
arr[i] = "%" + arrploicy[j] + "%";
++i;
}
query = query.substring(0, query.length - 3);
query += ") ";
}
I have a records which has data as 1234_456789. But it does not return any records, probably because it might be considering it as string.
You can use parameterized query without requering uou to escape. It is more secure too.

websql use select in to get rows from an array

in websql we can request a certain row like this:
tx.executeSql('SELECT * FROM tblSettings where id = ?', [id], function(tx, rs){
// do stuff with the resultset.
},
function errorHandler(tx, e){
// do something upon error.
console.warn('SQL Error: ', e);
});
however, I know regular SQL and figured i should be able to request
var arr = [1, 2, 3];
tx.executeSql('SELECT * FROM tblSettings where id in (?)', [arr], function(tx, rs){
// do stuff with the resultset.
},
function errorHandler(tx, e){
// do something upon error.
console.warn('SQL Error: ', e);
});
but that gives us no results, the result is always empty. if i would remove the [arr] into arr, then the sql would get a variable amount of parameters, so i figured it should be [arr]. otherwise it would require us to add a dynamic amount of question marks (as many as there are id's in the array).
so can anyone see what i'm doing wrong?
aparently, there is no other solution, than to manually add a question mark for every item in your array.
this is actually in the specs on w3.org
var q = "";
for each (var i in labels)
q += (q == "" ? "" : ", ") + "?";
// later to be used as such:
t.executeSql('SELECT id FROM docs WHERE label IN (' + q + ')', labels, function (t, d) {
// do stuff with result...
});
more info here: http://www.w3.org/TR/webdatabase/#introduction (at the end of the introduction)
however, at the moment i created a helper function that creates such a string for me
might be better than the above, might not, i haven't done any performance testing.
this is what i use now
var createParamString = function(arr){
return _(arr).map(function(){ return "?"; }).join(',');
}
// when called like this:
createparamString([1,2,3,4,5]); // >> returns ?,?,?,?,?
this however makes use of the underscore.js library we have in our project.
Good answer. It was interesting to read an explanation in the official documentation.
I see this question was answered in 2012. I tried it in Google 37 exactly as it is recommened and this is what I got.
Data on input: (I outlined them with the black pencil)
Chrome complains:
So it accepts as many question signs as many input parameters are given. (Let us pay attention that although array is passed it's treated as one parameter)
Eventually I came up to this solution:
var activeItemIds = [1,2,3];
var q = "";
for (var i=0; i< activeItemIds.length; i++) {
q += '"' + activeItemIds[i] + '", ';
}
q= q.substring(0, q.length - 2);
var query = 'SELECT "id" FROM "products" WHERE "id" IN (' + q + ')';
_db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, results1) {
console.log(results1);
debugger;
}, function (a, b) {
console.warn(a);
console.warn(b);
})
})

Column is not indexed even though it is. PreparedStatement inside

I'm really struggling with a bug that did not appear on my dev environment, only once deployed in test.
I'm using a prepared Statement to run around 30 000 query in a row. The query check for the similarity of a string with what's in our database, using the oracle fuzzy method.
The column checked is indexed, but, don't know why, it fails randomly after some iterations, saying that index does not exists.
I don't understand what's going on, as the index really exists. My method never rebuild or delete the index so there is no reason for this error to appear ...
public List<EntryToCheck> checkEntriesOnSuspiciousElement(List<EntryToCheck> entries, int type,int score, int numresults, int percentage) throws Exception {
Connection connection = null;
PreparedStatement statementFirstName = null;
PreparedStatement statementLastname = null;
int finalScore = checkScore(score);
int finalNumResults = checkNumResults(numresults);
int finalPercentage = checkPercentage(percentage);
try {
connection = dataSource.getConnection();
StringBuilder requestLastNameOnly = new StringBuilder("SELECT SE.ELEMENT_ID, SE.LASTNAME||' '||SE.FIRSTNAME AS ELEMENT, SCORE(1) AS SCORE ");
requestLastNameOnly.append("FROM BL_SUSPICIOUS_ELEMENT SE ");
requestLastNameOnly.append("WHERE CONTAINS(SE.LASTNAME, 'fuzzy({' || ? || '},' || ? || ',' || ? || ', weight)', 1)>? ");
requestLastNameOnly.append((type > 0 ? "AND SE.ELEMENT_TYPE_ID = ? " : " "));
requestLastNameOnly.append("ORDER BY SCORE DESC");
statementLastname = connection.prepareStatement(requestLastNameOnly.toString());
for (EntryToCheck entryToCheck : entries) {
ResultSet rs;
boolean withFirstName = (entryToCheck.getEntryFirstname() != null && !entryToCheck.getEntryFirstname().equals(""));
statementLastname.setString(1, entryToCheck.getEntryLastname().replaceAll("'","''"));
statementLastname.setInt(2, finalScore);
statementLastname.setInt(3, finalNumResults);
statementLastname.setInt(4, finalPercentage);
if(type > 0){
statementLastname.setInt(5, type);
}
System.out.println("Query LastName : " + entryToCheck.getEntryLastname().replaceAll("'","''") );
rs = statementLastname.executeQuery();
while (rs.next()) {
Alert alert = new Alert();
alert.setEntryToCheck(entryToCheck);
alert.setAlertStatus(new AlertStatus(new Integer(AlertStatusId.NEW)));
alert.setAlertDate(new Date());
alert.setBlSuspiciousElement(new BlSuspiciousElement(new Integer(rs.getInt("ELEMENT_ID"))));
alert.setMatching(rs.getString("ELEMENT") + " (" + rs.getInt("SCORE") + "%)");
entryToCheck.addAlert(alert);
}
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
finally {
DAOUtils.closeConnection(connection, statementLastname);
}
return entries;
}
Really don't know what to look at ...
Thanks !
F
I never used Oracle text tables but my advice is:
Make sure that no one else is executing DDL statements on the table simultaneously.
Also, make sure that, index you have is context index.
Create an index for your column where you want to apply search
........................................
CREATE INDEX "MTU219"."SEARCHFILTER" ON "BL_SUSPICIOUS_ELEMENT " ("LASTNAME")
INDEXTYPE IS "CTXSYS"."CONTEXT" PARAMETERS ('storage CTXSYS.ST_MTED_NORMAL SYNC(ON COMMIT)');
..........................................

How can I use the Twitter Search API to return all tweets that match my search query, posted only within the last five seconds?

I would like to use the API to return all tweets that match my search query, but only tweets posted within the last five seconds.
With Twitter's Search API, I can use the since_id to grab all tweets from a specific ID. However, I can't really see a good way to find the tweet ID to begin from.
I'm also aware that you can use "since:" in the actual query to use a date, but you cannot enter a time.
Can someone with Twitter API experience offer me any advice? Thanks for reading and your time!
http://apiwiki.twitter.com/Search-API-Documentation
This sounds like something you can do on your end, as created_at is one of the fields returned in the result set. Just do your query, and only use the ones that are within the last 5 seconds.
<script type="text/javascript" charset="utf-8">
// JavaScript Document
$(document).ready(function(){
// start twitter API
$.getJSON('http://twitter.com/status/user_timeline/YOUR_NAME.json?count=10&callback=?', function(data){
$.each(data, function(index, item){
$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');
});
});
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
}
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};// end twitter API
}); // ***** end functions *****
</script>
<div id="twitter">
Target Div
</div>
Are you trying to poll tweets in real time? Doesn't twitter have a limit on API req/hour. I think you'd hit that pretty fast.
Why don't you just make a call to the API every 5 seconds and grab the top 1 tweet.
Twitter API results are sorted by recent by default. Please see the following quote from twitter wiki :
Parameter to Twitter search API :
result_type: Optional. Specifies what type of search results you would prefer to receive.
* Valid values include:
o mixed: In a future release this will become the default value. Include both popular and real time results in the response.
o recent: The current default value. Return only the most recent results in the response.
o popular: Return only the most popular results in the response.
* Example: http://search.twitter.com/search.atom?q=Twitter&result_type=mixed
* Example: http://search.twitter.com/search.json?q=twitterapi&result_type=popular
* Example: http://search.twitter.com/search.atom?q=justin+bieber&result_type=recent
Please correct me if I am wrong anywhere.
Thanks and Regards,
Abhay Dandekar