html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<script>
// 返回数据库的实例
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024)
// 实例上调用方法,接收一个回调函数
db.transaction(function (tx) {
//tx 是一个SQLTransaction对象,后面的所有操作都基于该对象。
//创建表格
tx.executeSql('CREATE TABLE IF NOT EXISTS STU(stuId unique,stuName)')
//插入字段
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(111,222`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
tx.executeSql(`INSERT INTO STU(stuId,stuName) values(${Math.random()},${Math.random()})`)
})
// 查询
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM STU', [], function (tx, result) {
console.log(result.rows) //拿到数据
msg = `<p>查询到的数据条数一共有:${result.rows.length}条</p>`
content.innerHTML += msg
for (var i = 0; i < result.rows.length; i++) {
msg = `<p><b>${result.rows.item(i).stuName}</b></p>`
content.innerHTML += msg
}
}, null)
})
// 删除数据
db.transaction(function (tx) {
tx.executeSql('DELETE FROM STU WHERE stuId=?', [111])
})
// 修改数据
db.transaction(function (tx) {
tx.executeSql('UPDATE STU SET stuName=? WHERE stuId=2', ["寒冰"])
})
</script>
</body>
</html>