解析HTML5的存储功能和web SQL的相关操作方法

2020-04-25 07:58:59易采站长站整理

var db = openDatabase(‘mydb’, ‘1.0’, ‘Test DB’, 2 * 1024 * 1024);   
var msg;   
db.transaction(function (tx) {   
  tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)’);   
  tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (1, "foobar")’);   
  tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (2, "logmsg")’);   
  msg = ‘<p>Log message created and row inserted.</p>’;   
  document.querySelector(‘#status’).innerHTML =  msg;   
});   
  
db.transaction(function (tx) {   
  tx.executeSql(‘SELECT * FROM LOGS’, [], function (tx, results) {   
   var len = results.rows.length, i;   
   msg = "<p>Found rows: " + len + "</p>";   
   document.querySelector(‘#status’).innerHTML +=  msg;   
   for (i = 0; i < len; i++){   
     msg = "<p><b>" + results.rows.item(i).log + "</b></p>";   
     document.querySelector(‘#status’).innerHTML +=  msg;   
   }   
 }, null);   
});   
</script>   
</head>   
<body>   
<div id="status" name="status">Status Message</div>   
</body>   
</html>  

在浏览器中这会生成如下所示结果:

复制代码
Log message created and row inserted.</p>
<p>Found rows: 2</p>
<p>foobar</p>
<p>logmsg