Web SQL Database + Javascript loop

Asked
Active3 hr before
Viewed126 times

6 Answers

database
90%

It looks like the function is asynchronous, and that by the time tx.executeSql fires, the loop have finished looping and i has been changed several times., Where does the energy stored in inductor go on opening the switch? , What is an expedience of sci-fi gliders? these machines flying near the very ground ,Connect and share knowledge within a single location that is structured and easy to search.

Do it the other way around:

<script>
    numberofArticles = 5;
    db = openDatabase("websql", "0.1", "web-sql testing", 10000);
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, articleID int)');
    });
    db.transaction(function (tx) {  
        for (var i=0; i<=numberofArticles-1; i++){  
            tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)',  [i]);
        };
    });
</script>

And the alternative, the proper way with the loop outside which is unnecessary in this case

    for (var i = 0; i <= numberofArticles - 1; i++) {
       (function(i) {
          db.transaction(function(tx) {
             tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]);
          });
       })(i);
    };
load more v
88%

I'm trying to figure this out but can't seem to on my own... I'm playing with Web SQL DBs and I can't get a loop to work properly with it. I use:,You can solve this with a closure.,And I get only 5's.. I don't get the incremental i values. Can anyone suggestion what I'm doing wrong and what I should be thinking about? ,And the alternative, the proper way with the loop outside which is unnecessary in this case

I'm trying to figure this out but can't seem to on my own...
I'm playing with Web SQL DBs and I can't get a loop to work properly with it.
I use:

for (var i = 0; i <= numberofArticles - 1; i++) {
   db.transaction(function(tx) {
      tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]);
   });
};
load more v
72%

I'm trying to figure this out but can't seem to on my own... I'm playing with Web SQL DBs and I can't get a loop to work properly with it. I use:,And the alternative, the proper way with the loop outside which is unnecessary in this case,You can solve this with a closure.,Get answers to millions of questions and give back by sharing your knowledge with others.

I'm trying to figure this out but can't seem to on my own...
I'm playing with Web SQL DBs and I can't get a loop to work properly with it.
I use:

for (var i = 0; i <= numberofArticles - 1; i++) {
   db.transaction(function(tx) {
      tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]);
   });
};
load more v
65%

Our community of experts have been thoroughly vetted for their expertise and industry experience.,”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.,Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.


db = openDatabase('dbnames', '1.0', 'dbnames', 4 * 1024 * 1024);
db.transaction(function (tx) {
  		tx.executeSql('CREATE TABLE IF NOT EXISTS entries1 (id unique, headname, verse, vtext)');
});
		verse1=["JoeVerse", "BobVerse", "KenVerse"];
		headname1=["JoeHead", "BobHead", "KenHead"];
		vtext1=["JoeText", "BobText", "KenText"];

for(i = 0; i < 3; i++){
eid = i + 1;
eheadname = headname1[i];
evtext = vtext1[i];
everse = verse1[i];
insertdata(eid, eheadname, evtext, everse);
}

function insertdata(eid, eheadname, evtext, everse){
db.transaction(function (tx) {
    	tx.executeSql('INSERT INTO entries1 (id, headname, verse, vtext) VALUES (?, ?, ?, ?'), [eid, eheadname, everse, evtext];
		document.write(eid + " " + eheadname + " " + evtext + " " + everse + "<br>");
});
}
75%

SQL statement execution You can execute SQL statements asynchronously or synchronously. ,In the Web SQL Database API, each SQL statement must be executed under a transaction. To create a transaction, use either transaction() or readTransaction() method returned by the openDatabaseSync() method:,In the Web SQL Database API, each SQL statement must be executed under a transaction. To create a transaction, use either transaction() or readTransaction() method returned by the openDatabase() method:,To execute a SQL statement, use the executeSql() method. The SQL statement is the first parameter of the method and cannot contain SQL transaction statements (such as BEGIN, END, or ROLLBACK):

To open a database asynchronously, use the openDatabase() method. If the database does not exist, the method first creates it and then opens it:

var db;
var version = 1.0;
var dbName = 'tizendb';
var dbDisplayName = 'tizen_test_db';
var dbSize = 2 * 1024 * 1024;
try {
   db = openDatabase(dbName, version, dbDisplayName, dbSize, function(database) {
      alert('database creation callback');
   });
}

In the Web SQL Database API, each SQL statement must be executed under a transaction. To create a transaction, use either transaction() or readTransaction() method returned by the openDatabase() method:

db.transaction(function(t) {
   /* Place SQL statements here */
}, function() {
   alert('SQL statements were executed successfully.');
});

To execute a SQL statement, use the executeSql() method. The SQL statement is the first parameter of the method and cannot contain SQL transaction statements (such as BEGIN, END, or ROLLBACK):

t.executeSql('CREATE TABLE tizenTable (id INTEGER PRIMARY KEY, title TEXT, content TEXT, insertDay DATETIME)',
   [],
   function(sqlTransaction, sqlResultSet) {
      alert('Table has been created.');
   },
   function(sqlTransaction, sqlError) {
      /* Error handling */
   });

Pass arguments to the SQL statement:

sqlTransaction.executeSql('SELECT * FROM tizenTable WHERE id=?', [value]);

The result object of the INSERT statement contains the insert ID, which stores the identifier of the added record. If multiple records were inserted, the insert ID contains the ID of the last inserted record:

sqlTransaction.executeSql('INSERT INTO tizenTable(title, content, insertDay) VALUES (?, ?, ?)',
   [title, context, day],
   function(sqlTransaction, sqlResultSet) {
      alert('The '
         id ' of the new record  is ' + sqlResultSet.insertId);
   });

The result object of the SELECT statement stores also the number of records that were inserted, changed, or deleted. It contains the number of selected rows (length field) and the item() method. Use the method with the index argument (integer value from 0 to rows.length - 1) to get individual records:

sqlTransaction.executeSql('SELECT id, title, author FROM books', [], function(sqlTransaction, sqlResultSet) {
   var book, i, booksNumber = sqllResultSet.rows.length;
   for (i = 0; i < booksNumber; i++) {
      book = sqlResultSet.rows.item(i);
      alert('id: ' + book.id + ', title: ' + book.title +
         ', author: ' + book.author);
   }
});

To handle a syntax error asynchronously, use a sqlError object:

sqlTransaction.executeSql('SELECT * FROM notExistingTable', [], function(sqlTransaction, sqlResultSet) {},
   function(sqlTransaction, sqlError) {
      switch (sqlError.code) {
         case sqlError.SYNTAX_ERR:
            alert('Syntax error has occurred. ' + sqlError.message);
            break;
         default:
            alert('Other error');
      }
   });

To open a SQL database synchronously, use the openDatabaseSync() method. The method can only be used in the Web Worker context. If the database does not exist, the method first creates it and then opens it:

var databaseSync = null;
try {
   databaseSync = openDatabaseSync('dbName', '1.0', 'display database name', 1024 * 1024, function(databaseSync) {
      alert('database creation callback');
   });
}

In the Web SQL Database API, each SQL statement must be executed under a transaction. To create a transaction, use either transaction() or readTransaction() method returned by the openDatabaseSync() method:

database.transaction(function(sqlTransactionSync) {
   /* Place SQL statements here */
}, function() {
   alert('SQL statements were executed successfully.');
});

To execute a SQL statement, use the executeSql() method. The SQL statement is the first parameter of the method and cannot contain SQL transaction statements (such as BEGIN, END, or ROLLBACK):

var sqlResultSet = sqlTransactionSync.executeSql('CREATE TABLE IF NOT EXISTS books(id INTEGER PRIMARY KEY,
   title TEXT, author TEXT)
', []);

Pass arguments to the SQL statement:

var sqlResultSet = sqlTransactionSync.executeSql('SELECT id FROM books WHERE title=? AND author=?',
   ['Ulysses', 'James Joyce']);

The result object of the INSERT statement contains the insert ID, which stores the identifier of the added record. If multiple records were inserted, the insert ID contains the ID of the last inserted record:

var sqlResultSet = sqlTransactionSync.executeSql('INSERT INTO books (id, title, author) VALUES(NULL, ?, ?)',
   ['Ulysses', 'James Joyce']);
alert('The '
   id ' of the new record is ' + sqlResultSet.insertId);

The result object of the SELECT statement stores also the number of records that were inserted, changed, or deleted. It contains the number of selected rows (length field) and the item() method. Use the method with the index argument (integer value from 0 to rows.length - 1) to get individual records:

var sqlResultSet = sqlTransactionSync.executeSql('SELECT id, title, author FROM books');
var book, i, booksNumber = sqlResultSet.rows.length;
for (i = 0; i < booksNumber; i++) {
   book = sqlResultSet.rows.item(i);
   alert('id: ' + book.id + ', title: ' + book.title + ', author: ' + book.author);
}

To handle a syntax error synchronously, use a sqlException object:

try {
   databaseSync.transaction(function(sqlTransactionSync) {
      var sqlResultSet = sqlTransactionSync.executeSql('DELETE FROM books WHERE id=?', [id]);
   });
   /* Instructions if the above SQL statement is executed successfully */
} catch (sqlException) {
   postMessage('An error has occurred during deleting the book from the table!
      Error code: ' + sqlException.code + '(' + sqlException.message + ').
      ');
   }
load more v
40%

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:,If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.,Do not forget to increase the variable used in the condition, otherwise the loop will never end!,The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

let i = 0;
(i 10) {
   console.log(i);
   i++
}

Other "database-undefined" queries related to "Web SQL Database + Javascript loop"