Phonegap - Assemble with a query result from another query - Sqlite Query - sqlite

I can not make a selection via the result of the first
Goal is:
Do the query on the table "line" pick up your ID and search customers that line the "customer" table
This is my code:
db = window.openDatabase("test", "1.0", "Test DB", 1000000);
db.transaction(SelectData,erroSelect,sucessSelect);
function SelectData(tx)
{
tx.executeSql("select id from linha",[],function(tx, response)
{
for(i=0; i<response.rows.length; i++)
{
tx.executeSql("SELECT * FROM customers WHERE line= ?", [response.rows.item(i).id],
function (tx, results)
{
for(r=0; r<results.rows.length; r++)
{
alert(results.rows.item(r).nome); //never worked
}
}
}
},SelectError);
}

It is diffcult to understand from your post, where is the actual error.
Have you tried using console.log() call inside each tx.executeSql() to ascertain that the function is being executed.
Alternatively you can use a single query instead of using two SELECT statements.
Replace
select id from linha
with
SELECT customers.columnName1, customers.columnName2
FROM customers INNER JOIN linha ON customers.line = linha.id

Related

Bookshelf's nested query

I'm trying to get the following query in bookshelf's, any ideas? (this query is working and returns the required result)
SELECT "restaurants".*, "meals".*, ( select count(*) from "public"."visitors" as "visitors" where "visitors"."meal_id" = "meals"."id") as "visitorsMealsCount" FROM "public"."restaurants" as "restaurants" inner join "public"."meals" as "meals" ON "meals"."restaurant_id" = "restaurants"."id" WHERE "restaurants"."id" = '123'
Another question, after I'm using belongsTo and hasMany (for example) i expected the return object will be similar to that
restaurants (obj)
meals (obj)
visitorsMealsCount (attribute)
to me your SQL statement doesn't match the concept of an ORM tool like Bookshelf - it neither returns restaurants nor meals, but a grand mixture.
As to your second question: How about using new Restaurant({id: '123'}).fetch({ withRelated: ['meals']}) ?
visitorsMealsCount: In the documentation I see
adminAccounts: function() {
return this.belongsToMany(Account).query({where: {access: 'admin'}});
},
so maybe
visitorsMealsCount: function() {
return this.belongsToMany(Visitor).count();
}
works? (I haven't tried it.)

Go/golang sqlite query not returning any rows

I am new to go and trying to retrieve data from a sqlite database.
Im using github.com/mattn/go-sqlite3 as sqlite driver.
The query I m sending does not return any results even though it should. I tried the query my programme is generating manually and it returns data as it should when I use the query manually as well as when I send it via my programme.
Here is my code:
for index := range Array {
id, _ := strconv.Atoi(Array[index])
rand.Seed(time.Now().UnixNano())
RandomNr := rand.Intn(100)
fmt.Printf("index: %d - randomnr: %d \n", id, RandomNr)
rows, errROW := db.Query("SELECT user.id,user.name,stage.link,player.url,player.characterchance,player.chance FROM user,stage,player WHERE user.id = '%d' AND '%d' <= user.chance AND stage.user = user.id AND stage.domain = player.id AND player.chance > 0 ORDER BY player.id ASC \n",id, RandomNr)//.Scan(&idr, &name, &link, &url, &characterchance, &chance)
//this is what the finished query looks like and it returns the rows as its supposed to
//rows, errROW := db.Query("SELECT user.id,user.name,stage.link,player.url,player.characterchance,player.chance FROM user,stage,player WHERE user.id = '203' AND '33' <= user.chance AND stage.user = user.id AND stage.domain = player.id AND player.chance > 0 ORDER BY player.id ASC")
if errROW != nil {
fmt.Println("errROW")
log.Println(errROW)
}
defer rows.Close()
if rows.Next() == false {
fmt.Println("no rows ")
}
for rows.Next() {
fmt.Println("where are the rows")
var id int
var name string
var link string
var url string
var characterchance int
var chance int
rows.Scan(&id, &name, &link, &url, &characterchance, &chance)
fmt.Println(id,name,link,url,characterchance,chance)
}
rows.Close()
}
}
This query can return multiple and single rows. I also tried retrieving the data via QueryRow as a single row which also did not return any result.
Any help would be much appreciated.
UPDATE:
I added
if rows.Next() == false
as an attempt to find the problem. Removing it yields the same result. Furthermore I do not get an error message from scan. The for rows.next() loop does not even get executed.
when you do:
if rows.Next() == false
you are scrolling to the first row
and
for rows.Next()
moves to the next row
basically, you are skipping the first row in your result set in the example code you provided.
also, you are ignoring the error in Scan.
This looks like it would print something if the query returns at least 2 rows (since first row is being skipped)
Ok I figured out what the problem was:
In my query I used: %d as a placeholder for my variable when I should have used $1,$2 etc. Using this the query returns results as expected.
It seems strange to me that this behaviour is allowed returns no error from go or sqlite and even works when you just printout the query and use it with sqlite3 manually. Coming from C and just starting out with go this can obviously be the cause for some headaches.

ASP.NET my Linq code for nullable DateTime comparison is failing

My app allows user to upload an XML file, which I pass as an XDocument into my method. All the values are attribute strings, and I am using Linq to XML and Linq to SQL.
The dateCutoff query is supposed to get the latest date from SQL table - InsDate is nullable.
The where clause in the inspections XML query is supposed to get inspection elements with the inspection_date attribute value later than the dateCutoff value. I am using DateTime.Parse and Date.CompareTo, but am coming up empty.
What am I missing? Any help is much appreciated.
public IEnumerable<XElement> getInspections(XDocument xDoc)
{
IEnumerable<XElement> inspections = null;
using (InspectionDataContext db = new InspectionDataContext())
{
// get the latest date already in Inspections table
DateTime? dateCutoff = (from d in db.Inspections
select d.InsDate).Max();
if (dateCutoff.HasValue)
{
dateCutoff = dateCutoff.Value.Date;
}
// get only the inspections later than the dateCutoff
inspections = from i in xDoc.Descendants("inspections")
where DateTime.Parse(i.Element("inspection").Attribute("inspection_date").Value).Date.CompareTo(dateCutoff) == 1
select i;
}
return inspections;
}
I'm gong to make a few assumptions here because it's not totally clear as written.
1. You want to return "inspection" elements (not the "inspections" container elements).
2. You want to return only elements whose dates are greater than the cutoff
3. If the cutoff is null, you want to return all inspections.
In that case, you'd do something like this:
var inspections = xDoc.Descendents("inspection");
if (!dateCutoff.HasValue)
return inspections;
return inspections.Where(i => (DateTime)i.Attribute("inspection_date") > dateCutoff.Value )
Here is what works:
DateTime? dateCutoff;
using (InspectionDataContext db = new InspectionDataContext())
{
// get the latest date already in Inspections table
DateTime? dateCutoffQ = (from d in db.Inspections
select d.InsDate).Max();
if (dateCutoffQ.HasValue)
{
dateCutoff = dateCutoffQ.Value.Date;
}
else
{
dateCutoff = DateTime.Now.AddYears(-20).Date;
}
string date1 = dateCutoff.ToString();
// get only the inspections later than the dateCutoff
inspectionList = from i in xDoc.Descendants("inspection")
where DateTime.Parse(i.Attribute("inspection_date").Value).Date > dateCutoff
select i;

Faster database access by index

I have this code
using (var contents = connection.CreateCommand())
{
contents.CommandText = "SELECT [subject],[note] FROM tasks";
var r = contents.ExecuteReader();
int zaehler = 0;
int zielzahl = 5;
while (r.Read())
{
if (zaehler == zielzahl)
{
//access r["subject"].ToString()
}
zaehler++;
}
}
I want to make it faster by accessing zielzahl directly like r[zielzahl] instead of iterating through all entries. But
r[zielzahl]["subject"]
does not work aswell as
r["subject"][zielzahl]
How do I access the column subject of result number zielzahl?
To get only the sixth record, use the OFFSET clause:
SELECT subject, note
FROM tasks
LIMIT 1 OFFSET 5
Please note that the order of returned records is not guaranteed unless you use the ORDER BY clause.

NS_ERROR_FILE_IS_LOCKED when several requests using SQLite on Mozilla plateform

I'm trying to use Storage mechanism in Mozilla platform (in thundebird 3.0).
The following code is used after each test to erase the table present in the database:
function tearDown()
{
let database = new Database();
let req1 = "SELECT name FROM sqlite_master WHERE type='table'";
let statement = database.connection.createStatement(req1);
let tables = [];
while(statement.executeStep()) {
tables.push(statement.row.name);
}
statement.reset();
for(table in tables) {
let req2 = "DROP TABLE " + tables[table];
database.connection.executeSimpleSQL(req2);
}
}
But I've an error during executeSimpleSQL of req2 (NS_ERROR_FILE_IS_LOCKED), It seems that SQLite doesn't release the lock from the first statement. I've tried reset(), finalize(), but nothing works. How can I properly release the lock of the first statement?
Answering myself: I forgot to release a previous statement in previous code of my application.
Final story: when you use
statement.executeStep()
Check:
be sure that the last call of this statement return false
or never forgot to release it:
statement.reset();
var statement = dbConn.createStatement("SELECT COUNT(name) AS nameOcurrences FROM Table1 WHERE name = '" + aName + "';");
var occurrences;
while(statement.executeStep()) {
occurrences = statement.row.nameOcurrences;
}

Resources