I am trying to create a simple page that takes a binary file and inserts the values into a Web SQL database.
This is the function I am using to insert the data:
function bin2dbfunc()
{
var result, n, aByte, byteStr;
var i=0;
var sql = new Array();
result = fr.result; //Input file
for (n = 0; n < result.length; ++n)
{
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2)
{
byteStr = "0" + byteStr;
} //Format to add leading 0 for hex values
//Looping through taking each byte read from file and adding to array
//sql[i] = aByte; //Value
sql[i] = byteStr; //String
//When completed one row of database run single SQL insert statement with array contents
if(i==15)
{
i=0; //Clear counter for next row
db.transaction(function (tx)
{
tx.executeSql('INSERT INTO binary_data VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [sql[0], sql[1], sql[2], sql[3], sql[4], sql[5], sql[6], sql[7], sql[8], sql[9], sql[10], sql[11], sql[12], sql[13], sql[14], sql[15]]);
}, function (tx, err) {
document.getElementById("result3").innerHTML += 'ERROR '; //Display error message if SQL not run successfully
});
}
else
{
i++; //Otherwise increment counter
}
}
}
I have stripped back the code to remove all my debug messages but essentially the code appears to run. I am using a binary file with 6 rows worth of data, the code however inserts the last row of data 6 times into the database.
Can anyone spot where I am going wrong?
Variables are captured by reference and not by value in JavaScript closures (this is true for objects such as arrays but for primitive values as well); this means that the functions passed to
db.transactionwill use the current value ofsqlwhen they run. It seems that they run asynchronously in your case, thus using the value ofsqloncebin2dbfunchas returned (which explains why you end up with the last row of data).You have to copy the value of
sqlin order to make sure that the right one is used:or
as you don’t need
sql‘s values afterwards inbin2dbfunc; this second solution would also enable you to get rid ofiand use a more elegant solution based onpushandlength.