通过简单的SQL语句实现对数据库的增删改查。
窗口如下:
定义打开与关闭连接函数,方便每次调用:
增加指令:
删除指令:
修改指令:
查找指令:
表格情况:
一、数据库
- 数据库;存放数据的仓库
- 如果把数据存放在一个文本文件中,有很多的缺点:
a.可以任意修改/删除/新增
b.检索不便
c.信息不安全- 数据库系统;就能方便解决上述问题.
常用的数据库系统:MySal Oracle sQlserver…二、数据库的增删改查操作
增删查改语句
增删查改的意思·增:新增记录insert
.删:删除记录delete
·查:查询记录select
·改:修改记录updateinsert语句
insert语句对应的是"增”,也即新增数据
基本用法:insert into表名(字段名)values(值);
例:
insert into student(name , age)values(' andy' ,20);
代表给student表新增—条数据,name的值为andy,age的值为20。
delete语句
delete语句是删除语句
语法:
delete from 表名 where 条件
例子
delete from user where id > 4;
注意:
如果没有条件语句,将删除所有数据
delete from user;
update 语句
update语句是修改数据
语法:update 表名 set 字段名1 = 新增1,字段名2 = 新值2 where 条件
例子
update user set username = '花木兰',description = '兰陵王' where id = 3;
注意
如果没有条件语句,将更改所有数据
update user set username = '百里守约',description = '玄策的哥哥';
select语句
语法:select * from 表名
例子
select * from user where id = 3;
三、nodejs操作数据库-查
// 导包 var mysql = require('mysql'); // 创建一个和数据库的连接 var connection = mysql.createConnection({ host : 'localhost', // 数据库副武器的地址 user : 'root', // 账号 password : '185345', // 密码 database : '电光耗子' // 数据库名 }); // 打开连接 connection.connect(); // 执行SQL语句 connection.query('select * from user', function (error, results, fields) { // 错误对象,如果没有错误就返回null // console.log(error); // 执行sql语句得到的结果集,有错的话就是undefined。 console.log(results); console.log(results[2].username); // 拿到的是字段的信息 // console.log(fields); }); // 关闭连接 connection.end();
在实现简单网页上对数据内容进行增删改查,需要用到三个部分,分别是jsp网页部分+java后台部分+数据库表
我用一个新闻的例子来实现,首先编写java后台程序
java后台程序:
我们用三层的模式进行设计:分别是servlet,service,dao层,并且建立个实体包用来打包数据库和后台要用到的属
性截个图
首先是写功能写的顺序分别是从servlet,service,dao层:
servlet层代码如下:
public class TypeServlet { TypeService ts=new TypeServiceImp();//调用service层 /*******添加************************************************************************************/ public int addtype(String name){ int a=0; a=ts.addtype(name); return a; } /*******查看************************************************************************************/ public List<types> selets(){ List<types> list=new ArrayList<types>(); list=ts.selets(null); return list; } /*******删除************************************************************************************/ public int delete(int id){ int a=0; types t=new types(); t.setId(id); a=ts.delete(t); return a; } /*******修改************************************************************************************/ public int update(types t){ int a=0; a=ts.update(t); return a; } /*******查找一个************************************************************************************/ public types selectone(int id){ types t=new types(); t.setId(id); types nt=ts.selectone(t); return nt; } }
Service层分为两层分别为接口层和实现层
接口程序如下:
public interface TypeService { public int addtype(String name); public List<types> selets(types t); public int delete(types t); public int update(types t); public types selectone(types t); }
接口实现程序:
public class TypeServiceImp implements TypeService{ TypeDao td= new TypeDaoImp(); public int addtype(String name) { //注意返回数据不要忘记修改 int a=0; a=td.addtype(name); return a; } public List<types> selets(types t) { List<types> list=new ArrayList<types>(); list=td.selets(t); return list; } /*******删除************************************************************************************/ public int delete(types t) { int a=0; a=td.delete(t); return a; } /*******修改************************************************************************************/ public int update(types t) { int a=0; a=td.update(t); return a; } /*******查找单个************************************************************************************/ public types selectone(types t){ types tp=new types(); tp=td.selectone(t); return tp; } }
Dao层程序同样分为接口层和实现层
接口层程序:
public interface TypeDao { public int addtype(String name); public List<types> selets(types t); public int delete(types t); public int update(types t); public types selectone(types t); }
实现类程序:
public class TypeDaoImp implements TypeDao{ Connection con=null; PreparedStatement ps=null; ResultSet rs=null; public int addtype(String name){ int a=0; try { //连接数据库 con=Shujuku.conn(); String sql="insert into typesname values(?)"; //设置id自增 ps=con.prepareStatement(sql); ps.setString(1, name); a=ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return a; } public List<types> selets(types t) { List<types> list=new ArrayList<types>(); try { //连接数据库 con=Shujuku.conn(); String sql="select*from typesname"; ps=con.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()){ types ty=new types(); ty.setId(rs.getInt("id")); ty.setTypename(rs.getString("typename")); list.add(ty); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } /*******删除************************************************************************************/ public int delete(types t) { int a=0; try { con=Shujuku.conn(); String sql="delete from typesname where id="+t.getId(); ps=con.prepareStatement(sql); a=ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return a; } /*******修改************************************************************************************/ public int update(types t) { int a=0; try { con=Shujuku.conn(); String sql="update typesname set typename=? where id=?"; ps=con.prepareStatement(sql); ps.setString(1, t.getTypename()); ps.setInt(2, t.getId()); a=ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return a; } /*******查找一个************************************************************************************/ public types selectone(types t) { types tp=new types(); try { con=Shujuku.conn(); String sql="select * from typesname where id=?"; ps=con.prepareStatement(sql); ps.setInt(1, t.getId()); rs=ps.executeQuery(); if(rs.next()){ tp.setId(rs.getInt("id")); tp.setTypename(rs.getString("typename")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tp; } }
最后就是数据库包,为了方便使用,将数据库的驱动连接信息建立一个包存放:
代码如下:
public class Shujuku { public static Connection conn(){ //定义地址 String url="jdbc:sqlserver://localhost:1433;DatabaseName=test;"; //定义连接初始值 Connection connection=null; try { //加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //建立连接 connection=DriverManager.getConnection(url, "sa", "DCX5201314"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } }
属性包,代码如下:
public class types { private int id; private String typename; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } }
java后台程序就这么多;
接下来是数据库部分:
数据库部分主要就是建立一张表,笔者使用的是SQL Server 2008,首先建个数据库test,建立个表typesname,设置两列分别为id typename,id设为主键,int 型,自增为1;typename设置类型为varchar型,不能为空。
好了,数据库和java后台都搭建好了,现在来到前端网页部分,
网页部分
在myeclipse中新建7个jsp文件
index.jsp是一个总的网页
设置代码如下:
</head> <frameset rows="20%,80%"> <frame src="head.jsp"> <frameset cols="20%,80%"> <frame src="left.jsp"> <frame src="right.jsp" name="rights"> </frameset> </frameset> <body> </body>
head.jsp
<body> <h1>这是头部</h1> </body>
left.jsp
<body> <h1>这是左边</h1> <ul> <li><a href="addtype.jsp" target="rights">添加新闻类型</a></li> <li><a href="showtype.jsp" target="rights">查看新闻类型</a></li> </ul> </body>
right.jsp
<body> <h1>这是右边</h1> </body>
addtype.jsp
</head> <% request.setCharacterEncoding("UTF-8"); String name= request.getParameter("typename"); if(name!=null){ TypeServlet tp=new TypeServlet(); int a=tp.addtype(name); if(a>0){ RequestDispatcher rd = request .getRequestDispatcher("showtype.jsp"); rd.forward(request, response); }else{ RequestDispatcher rd = request .getRequestDispatcher("addtype.jsp"); rd.forward(request, response); } } %> <body> <h1>添加新闻类型</h1><hr/> <form action="addtype.jsp" method="post"> 新闻类型:<input type="text" name="typename"></br> <input type="submit" value="提交"> </form> </body>
showtype.jsp
<script type="text/javascript"> function deletes_(id){ var f=confirm("是否确定删除?"); if(f){ location.href="showtype.jsp?ids="+id; }else{ alert("您取消删除"); } } function update(id){ location.href="updatetype.jsp?ids="+id; } </script> </head> <% request.setCharacterEncoding("UTF-8"); String id=request.getParameter("ids"); String type=request.getParameter("type"); if(id!=null){ TypeServlet ts=new TypeServlet(); int a = ts.delete(Integer.parseInt(id)); response.sendRedirect("showtype.jsp"); } %> <body> <h1> 展示类型</h1> <table border="1"> <tr><td>编号</td><td>类型名称</td><td>操作</td></tr> <% //直接调用后台数据 TypeServlet ts=new TypeServlet(); List<types> list=ts.selets(); for(int i=0;i<list.size();i++){ types n=list.get(i); %> <tr> <td><%=n.getId() %></td> <td><%=n.getTypename() %></td> <td><input type="button" onclick="update(<%=n.getId() %>)" value="修改"/> <input type="button" onclick="deletes_(<%=n.getId() %>)" value="删除"/></td> </tr> <% } %> </body>
updatetype.jsp
<body> <% request.setCharacterEncoding("UTF-8"); String id=request.getParameter("ids"); TypeServlet tsl=new TypeServlet(); types ts=new types(); String type= request.getParameter("type"); if(type!=null){ String typename=request.getParameter("newtype");//从下面的输入取值 String id1=request.getParameter("id"); ts.setId(Integer.parseInt(id1));//强转 ts.setTypename(typename); int a=tsl.update(ts); response.sendRedirect("showtype.jsp"); }else{ if(id!=null){ ts=tsl.selectone(Integer.parseInt(id)); } } %> <h1>修改新闻类型界面</h1> <hr/> <form action="updatetype.jsp" method="post"> <input type="hidden" name="type" value="3"> <input type="hidden" name="id" value="<%=ts.getId() %>"> 新闻类型:<input type="text" value="<%=ts.getTypename() %>" name="newtype"><br/> <input type="submit" value="提交"> </form> </body>
最终项目在tomcat上发布。
下面的地址积分系统调的太高了,我重新上传了一份内容是一样的地址在这:http://download.csdn.net/download/qq_34178998/10154005
高积分下载打包文件在这:http://download.csdn.net/download/qq_34178998/9920064
也可以参考在这篇基础上的两个表关联操作:http://blog.csdn.net/qq_34178998/article/details/77017760
有问题也希望各位提出,一起进步,
没积分的留言。留下邮箱,我看到会给你发的,但是太多的,可能会漏发,见谅!!!
也欢迎转载!!!也欢迎转载!!!也欢迎转载!!!
需要代码的人多,直接上传百度云了,大家自己下载,喜欢的话给我点个赞 链接:https://pan.baidu.com/s/1YPUWpI4A3Q54V0_d-cunxg 提取码:pzey
点个赞点个赞点个赞点个赞点个赞
nodejs结合Mongodb,实现数据库的增删改查
1.安装mongoose
首先安装mongoose插件,在控制台输入如下命令。
cnpm i mongoose -S
-S --save
-D --save-dev2.连接数据库
2.1 确保数据库连接池是已打开状态(准备工作)
D盘mongodb文件夹内解压下载好的mongodb文件,D盘根目录下创建一个文件夹data,在data内部再创建一个文件夹db。
进入mongodb的bin目录,按住Shift键,空白处再点击鼠标右键,打开命令行窗口,输入下面的指令。mongod --dbpath d:\data\db
2.2 新建一个db.js文件,准备连接数据库
const mongoose = require('mongoose'); const DB_URL = 'mongodb://127.0.0.1:27017/sh1902'; mongoose.connect(DB_URL, { useNewUrlParser: true }); mongoose.connection.on('connected', () => { console.log('数据库已经连接成功'); }); mongoose.connection.on('disconnected', () => { console.log('数据库连接失败'); }); mongoose.connection.on('error', () => { console.log('数据库连接异常'); });
在控制台输入node db.js指令,应出现“数据库连接成功”的字样。
2.3 生成自定义模块
依据模块化开发,需要将db.js连接数据库的文件暴露出去,生成一个自定义模块。
const mongoose = require('mongoose'); const DB_URL = 'mongodb://127.0.0.1:27017/sh1902'; mongoose.connect(DB_URL, { useNewUrlParser: true }); mongoose.connection.on('connected', () => { console.log('数据库已经连接成功'); }); mongoose.connection.on('disconnected', () => { console.log('数据库连接失败'); }); mongoose.connection.on('error', () => { console.log('数据库连接异常'); }); module.exports = mongoose;
3. 设计用户数据表
设计数据表的形式,暴露数据模型,并在数据库中创建一个集合。
创建一个名为user.js的文件。const mongoose = require('./db.js'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String }, password: { type: String }, age: { type: Number }, tel: { type: String }, sex: { type: String }, city: { type: String } }); // 执行时 会在数据库中创建users集合 module.exports = mongoose.model('User', UserSchema);
注意
module.exports = mongoose.model('User', UserSchema);
其中的User为自定义名称,数据库中会出现其复数的集合。例如:
module.exports = mongoose.model(‘Test’, UserSchema);
此时,数据库会出现tests的集合。
4. 增删改查操作
4.1 增
新建insert.js用来添加新用户
// 插入用户 const User = require('./users'); const user = new User({ username: '李思思', password: '123', age: 22, tel: '13248099856', sex: '女', city: '山西' }) user.save((err) => { if (err) throw err; console.log('用户插入成功') })
4.2 删
新建一个delete.js文件
const User = require('./users'); //第一种写法 // User.deleteOne({username: '李思思'}, err => { // if (err) throw err; // console.log('删除成功') // }) // style.display = 'flex' <==> style['display'] = 'flex' //第二种写法 User['deleteOne']({username: '李思思'}, err => { if (err) throw err; console.log('删除成功') })
4.3 改
新建update.js用来修改数据
const User = require('./users'); User.updateOne({username: '李思思'}, {$set: {age: 20}}, err => { if (err) throw err; console.log('修改成功') }) User.updateMany({}, {$set: {city:'江苏'}}, err => { if (err) throw err; console.log('修改成功') })
4.4 查
新建find.js用来测试增删改相关文件的功能,也可以用来查询数据库。
const User = require('./users'); User.find({}, {}, (err, data) => { if (err) throw err console.log(data) })
另一种查询数据库的写法,可添加排序功能。(推荐)
const User = require('./users'); User.find({}, {_id: 0, __v: 0}).sort({age: 1}).exec((err, data) => { if (err) throw err; console.log(data) })
5. 封装数据库模块
5.1 目录结构
sql model user.js db.js index.js
其中,users.js文件和db.js文件为之前所写文件,唯一有所变化的部分是user.js引入db.js的路径需要修改。
5.2 封装数据库增删改查
index.js为新建封装数据库的增删改查文件,同时使用promise方法解决异步数据问题。
const sql = { //增 insert(Collection, insertobj) { return new Promise((resolve, reject) => { Collection.insertMany(insertobj, (err) => { if (err) throw err; resolve(); }) }) }, //删 delete(Collection, whereobj, type) { return new Promise((resolve, reject) => { let deletetype = 'deleteOne'; type === 1 ? deletetype = 'deleteMany' : deletetype = 'deleteOne'; Collection[deletetype](whereobj, (err) => { if (err) throw err; resolve(); }) }) }, //改 update(Collection, whereobj, updateobj, type) { return new Promise((resolve, reject) => { let updatetype = 'updateOne'; type === 1 ? updatetype = 'updateMany' : updatetype = 'updateOne'; Collection[updatetype](whereobj, updateobj, (err) => { if (err) throw err; resolve(); }) }) }, //查 find(Collection, whereobj, showobj) { return new Promise((resolve, reject) => { Collection.find(whereobj, showobj).exec((err, data) => { if (err) throw err; resolve(data); }) }) } } module.exports = sql;
5.3 测试数据库的增删改查
测试文件的封装,可立刻检查功能是否实现
插入功能测试文件insertdata.jsconst sql=require('./sql'); const User=require('./sql/model/user'); sql.insert(User,{ username:'李四', password:'222', age:34, tel:'13824586557' }).then(()=>{ console.log('success'); sql.find(User,{},{}).then(data=>{ console.log(data); }) })
删除功能测试文件deletedata.js
const sql=require('./sql'); const User=require('./user'); sql.delete(User,{username:'王富贵'}).then(()=>{ console.log('success'); sql.find(User,{},{}).then(data=>{ console.log(data) }) })
修改功能测试文件updatedata.js
const sql=require('./sql'); const User=require('./sql/model/user'); sql.update(User,{username:'张夏'},{$set:{age:11}}).then(()=>{ console.log('success'); sql.find(User,{},{}).then(data =>{ console.log(data); }) })
查询功能测试文件find.js
const sql = require('./sql'); const User = require('./sql/model/user'); sql.find(User,{},{}).then(data=>{ console.log(data); })
通过简单的SQL语句实现对数据库的增删改查。
窗口如下:
定义打开与关闭连接函数,方便每次调用:
增加指令:
删除指令:
修改指令:
查找指令:
表格情况:
转载于:https://www.cnblogs.com/moon-boke/p/11413648.html