I'm trying to make my code better by being more specific with the SQL queries:
The following code works and I can work with the results. But probably not the most efficient:
function queryDB(tx) {
tx.executeSql('SELECT * FROM foo', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: JOHN
So when I try:
function queryDB(tx) {
tx.executeSql('SELECT id FROM foo WHERE id = 1', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: undefined
I've tried using different numbers on the query and on the array but nothing works. I assume that the query is wrong.
Thanks!
I'm trying to make my code better by being more specific with the SQL queries:
The following code works and I can work with the results. But probably not the most efficient:
function queryDB(tx) {
tx.executeSql('SELECT * FROM foo', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: JOHN
So when I try:
function queryDB(tx) {
tx.executeSql('SELECT id FROM foo WHERE id = 1', [], querySuccess);
}
function querySuccess(tx, results) {
console.log(results.rows.item(0).name);
}
OUTPUT: undefined
I've tried using different numbers on the query and on the array but nothing works. I assume that the query is wrong.
Thanks!
Share Improve this question asked Sep 4, 2012 at 4:58 ricardoloboricardolobo 773 silver badges8 bronze badges 1- 1 You are selecting id but your output is name – house9 Commented Sep 4, 2012 at 5:01
2 Answers
Reset to default 3Well, for a start do you have a row where the ID is 1?
Secondly, since you're only selecting the id
column in your second statement, why do you think you're going to be able to access name
?
Thirdly, it makes little sense to limit your query to the first row without an order by
clause. SQL is free to return the rows in any order it wants without that clause.
If you really want the name for the first ID in the table, something like:
select name from foo order by id limit 1
should do the trick. There are very few use cases where it makes sense to do select *
.
If you want the fourth row, use something like:
select name from foo order by id limit 1 offset 3
See here for more details.
Add LIMIT 1
to your query. Here is example:
SELECT * FROM foo LIMIT 1