实现数据库存储账号密码 并实现增删查的简单功能
效果如下:
屏幕快照 2017-05-26 09.39.31.png
首先引入:jquery-1.10.2.min.js 放在js文件夹下
<script src="js/jquery-1.10.2.min.js"></script>
下载链接:https://pan.baidu.com/s/1jIFUVem
1.页面代码如下
<body>
<div>//添加div
<input type="text" autofocus="autofocus" required="required" placeholder="请输入账号" id="userName" />
<input type="password" required="required" placeholder="请输入密码" id="password" />
<input type="button" value="添加" onclick="add()" />
</div>
<div>//查询div
<input type="text" placeholder="请输入要查询的账号" id="sel"/>
<input type="button" value="查询" onclick="sel()" />
</div>
<div>//删除div
<input type="text" name="" placeholder="请输入要删除的账号" id="text" />
<input type="button" value="删除" onclick="del()"/>
</div>
<div id="dCon">//显示数据查询结果div
</div>
</body>
2.创建数据库访问对象
<script type="text/javascript">
/* openDatabase(
name: String, //数据库名称
version: String, //数据库版本号
isplayName: String, //数据库描述
estimatedSize: Number,//数据库大小
creationCallback: DatabaseCallback//回调
): Database */
var db = openDatabase("myDB", "1.0", "text db", 2014 * 10)
</script>
3.添加数据
<script type="text/javascript">
function add() { //添加
//transaction(storeNames: String, mode: String): IDBTransaction
db.transaction( //开启一个事务
function(fx) {
//executeSql(sqlStatement: String, arguments: Array): SQLResultSet
//创建表格
fx.executeSql("create table if not exists UserInfor(UserName TEXT,Pwd TEXT)", [])
var userName = $('#userName').val()
var passWord = $('#password').val()
console.log(userName)
console.log(passWord)
//插入数据
fx.executeSql("insert into UserInfor values(?,?)", [userName, passWord])
}
)
}
</script>
4.查询数据
<script type="text/javascript">
function sel() { //查询
var sql = 'select * from UserInfor where 1=1 '
var username = $('#sel').val()
if(username != '') {
sql += 'and UserName=' + username + ''
}
console.log(sql)
//开启一个事务
db.transaction(function(fx) {
$("#dCon").html("")
fx.executeSql(sql, [], function(fx, res) {
for(var i = 0; i < res.rows.length; i++) {
console.log(res.rows[i].UserName)
console.log(res.rows[i].Pwd)
var s = '<div>' + res.rows[i].UserName + '-------' + res.rows[i].Pwd + '</div>'
$('#dCon').append(s)
}
})
})
}
</script>
5.删除数据
<script type="text/javascript">
function del(){//删除
var sql = 'delete from UserInfor where UserName='
var username = $('#text').val()
if(username != '') {
sql += username
}
//开启一个事务
db.transaction(function(fx) {
fx.executeSql(sql, [], function() {
console.log('删除成功')
sel()
})
})
}
</script>
运行结果:
屏幕快照 2017-05-26 10.18.36.png
网友评论