Reputation: 1048
I tried to insert some data into web sql database.But I met a problem.
My code :
database();
for(var i=0;i<m.length;i++){
showid = m[i].id;
showtitle = m[i].title;
insert();
}
function database(){
//open the database
db = window.openDatabase("youyanchu", "1.0","youyanchu",500000);
db.transaction(function(tx) {
var table = tx.executeSql("CREATE TABLE showList (id int PRIMARY KEY, title NVARCHAR, finishDate NVARCHAR, status NVARCHAR, tkCount NVARCHAR )");
});
}
//INTEGER NOT NULL PRIMARY KEY
function insert(){
db.transaction(function(ar) {
ar.executeSql("INSERT INTO showList (id, title,finishDate,status) values(?,?,?,?)", [showid,showtitle,'aaa','bbb']);
});
}
m.length is 3 and "m" should be
aaa = {'id':'999','title':'ninini'}
bbb = {'id':'888','title':'ninini'}
ccc = {'id':'777','title':'ninini'}
At last,just "ccc" display in the web sql.
How to insert all data into the database?What mistake I made in the code?
Upvotes: 0
Views: 231
Reputation: 2100
Since tx.executeSql
is asynchronous, I believe your loop
finishes before the first insert
runs.
Hence showid
and showtitle
will always have the last values of the object m
Try this instead:
for(var i=0;i<m.length;i++){
insert(m[i].id, m[i].title);
}
function insert(id, title){
db.transaction(function(tx) {
txexecuteSql("INSERT INTO showList (id, title,finishDate,status) values(?,?,?,?)", [id, title,'aaa','bbb']);
});
}
Upvotes: 2