基本的CRUD操作

导入包---实体类------数据库连接----数据库操作----service层数据操作----网页对service层可视化实现
model
package com.ij34.model;
public class article {
private int id;
private String title;
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
dao
package com.ij34.dao;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class DbConn {
private static String username="root";
private static String password="123456";
private static String url="jdbc:mysql://localhost:3306/articles?useUnicode=true&characterEncoding=UTF-8";
private static Connection conn=null;
public static Connection getConnection(){
if(conn==null){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=(Connection) DriverManager.getConnection(url, username, password);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return conn;
}
//test connection
public static void main(String[] args) {
DbConn db=new DbConn();
System.out.println(db.toString());
}
}
package com.ij34.dao; import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import com.ij34.model.article;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement; public class ArticleDao { public List<article> getfindAll(){ //查All,返回list
List<article> list=new ArrayList<article>();
String sql="select * from article";
Connection conn=DbConn.getConnection();
try {
PreparedStatement pstm=(PreparedStatement) conn.prepareStatement(sql);
ResultSet rs=pstm.executeQuery();
while(rs.next()){
article art=new article();
art.setId(rs.getInt("id"));
art.setTitle(rs.getString("title"));
art.setContent(rs.getString("content"));
list.add(art);
}
rs.close();
pstm.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list; } public boolean addArticle(article art){ //增
String sql="insert into article(title,content)values(?,?)";
Connection conn=DbConn.getConnection();
try {
PreparedStatement pstm=(PreparedStatement) conn.prepareStatement(sql);
pstm.setString(1, art.getTitle());
pstm.setString(2, art.getContent());
int count=pstm.executeUpdate();
pstm.close();
if(count>0) return true;
else return false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false; } public boolean updateArticle(article art){ //修改
String sql="update article set title=?,content=? where id=?";
Connection conn=DbConn.getConnection();
try {
PreparedStatement pstm=(PreparedStatement) conn.prepareStatement(sql);
pstm.setString(1, art.getTitle());
pstm.setString(2, art.getContent());
pstm.setInt(3, art.getId());
int count=pstm.executeUpdate();
pstm.close();
if(count>0) return true;
else return false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false; } public boolean deleteArticle(int id){ //删除,根据id
String sql="delete from article where id=?";
//String sql="delete from article where id='"+id+"'";
Connection conn=DbConn.getConnection();
try {
PreparedStatement pstm=(PreparedStatement) conn.prepareStatement(sql);
pstm.setInt(1, id);
int count=pstm.executeUpdate();
pstm.close();
if(count>0) return true;
else return false;
} catch (Exception e) {
e.printStackTrace();
}
return false; } public article selectById(int id){//根据id查找
String sql="select * from article where id="+id;
Connection conn=DbConn.getConnection();
article art=null;
try {
PreparedStatement pstm=(PreparedStatement) conn.prepareStatement(sql);
ResultSet rs=pstm.executeQuery();
while(rs.next()){
art=new article();
art.setId(rs.getInt("id"));
art.setTitle(rs.getString("title"));
art.setContent(rs.getString("content"));
}
rs.close();
pstm.close();
} catch (Exception e) {
e.printStackTrace();
}
return art;
}
}
service
add
package com.ij34.service; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.ij34.dao.ArticleDao;
import com.ij34.model.article; public class addArticle extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
article art=new article();
String title=req.getParameter("title");
String content=req.getParameter("content");
art.setTitle(new String(title.getBytes("ISO-8859-1"),"UTF-8"));
art.setContent(new String(content.getBytes("ISO-8859-1"),"UTF-8"));
ArticleDao ad=new ArticleDao();
ad.addArticle(art);
req.getRequestDispatcher("showArticle").forward(req, resp);
} }
del
package com.ij34.service; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.ij34.dao.ArticleDao; public class deleteArticle extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String idStr=req.getParameter("id");
if(idStr!=null&&!idStr.equals("")){
int id=Integer.valueOf(idStr);
ArticleDao ad=new ArticleDao();
ad.deleteArticle(id);
}
req.getRequestDispatcher("showArticle").forward(req, resp);
} }
find
package com.ij34.service; import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.ij34.dao.ArticleDao;
import com.ij34.model.article; public class showArticle extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ArticleDao ad=new ArticleDao();
List<article> list=ad.getfindAll();
req.setAttribute("list", list);
req.getRequestDispatcher("show.jsp").forward(req, resp);
} }
update
package com.ij34.service; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.ij34.dao.ArticleDao;
import com.ij34.model.article; public class updateArticle extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String idStr=req.getParameter("id");
if(idStr!=null&&!idStr.equals("")){
ArticleDao ad=new ArticleDao();
int id=Integer.valueOf(idStr);
article art=ad.selectById(id);
req.setAttribute("article", art);
}
req.getRequestDispatcher("update.jsp").forward(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
article art=new article();
String idStr=req.getParameter("id");
String title=req.getParameter("title");
String content=req.getParameter("content");
art.setId(Integer.valueOf(idStr));
art.setTitle(new String(title.getBytes("ISO-8859-1"),"UTF-8"));
art.setContent(new String(content.getBytes("ISO-8859-1"),"UTF-8"));
ArticleDao ad=new ArticleDao();
ad.updateArticle(art);
req.getRequestDispatcher("showArticle").forward(req, resp);
} }
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Articles</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>addArticle</servlet-name>
<servlet-class>com.ij34.service.addArticle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addArticle</servlet-name>
<url-pattern>/addArticle</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>deleteArticle</servlet-name>
<servlet-class>com.ij34.service.deleteArticle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>deleteArticle</servlet-name>
<url-pattern>/deleteArticle</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>showArticle</servlet-name>
<servlet-class>com.ij34.service.showArticle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showArticle</servlet-name>
<url-pattern>/showArticle</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>updateArticle</servlet-name>
<servlet-class>com.ij34.service.updateArticle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>updateArticle</servlet-name>
<url-pattern>/updateArticle</url-pattern>
</servlet-mapping>
</web-app>
网页
index
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:forward page="showArticle"/> //要写doget
add
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添 加</title>
</head>
<body>
<form action="addArticle" method="post">
<table align="center">
<tr>
<td colspan="2"><center><h4>添加</h4></center></td>
</tr>
<tr>
<td>标 题:</td><td><input type="text" name="title"/></td>
</tr>
<tr>
<td>内 容:</td><td><input type="text" name="content"/></td>
</tr>
<tr>
<td><input type="submit" value="提 交"/></td><td><input type="reset" value="重 置"/></td>
</tr>
</table>
</form>
</body>
</html>
update
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修 改</title>
</head>
<body>
<form action="updateArticle" method="post">
<table align="center">
<tr>
<td colspan="2"><center><h4>修 改</h4></center></td>
</tr>
<tr>
<td>编 号:</td><td><input type="text" name="id" value="${article.id }" readonly="readonly"/></td>
</tr>
<tr>
<td>标 题:</td><td><input type="text" name="title" value="${article.title }"/></td>
</tr>
<tr>
<td>内 容:</td><td><input type="text" name="content" value="${article.content }"></td>
</tr>
<tr>
<td><input type="submit" value="提 交"/></td><td><input type="button" value="返回" onclick="history.go(-1)"/></td>
</tr>
</table>
</form>
</body>
</html>
show
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示</title>
</head>
<body>
<form action="showArticle" method="post">
<table align="center">
<tr>
<th>编 号 </th>
<th>标 题 </th>
<th> 内 容 </th>
<th> 操 作 </th>
</tr> <c:forEach var="li" items="${list}">
<tr>
<td>${li.id} </td>
<td> ${li.title} </td>
<td> ${li.content} </td>
<td><a href="deleteArticle?id=${li.id}">删除</a>|<a href="updateArticle?id=${li.id}">修改</a></td>
</tr>
</c:forEach> <tr>
<td align="center"><a href="add.jsp"> 添 加 </a></td>
</tr>
</table>
</form>
</body>
</html>
结果

基本的CRUD操作的更多相关文章
- 【翻译】MongoDB指南/CRUD操作(四)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...
- 【翻译】MongoDB指南/CRUD操作(三)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...
- 【翻译】MongoDB指南/CRUD操作(二)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...
- 【翻译】MongoDB指南/CRUD操作(一)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...
- ASP.NET Core Web API Cassandra CRUD 操作
在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...
- MongoDB的CRUD操作
1. 前言 在上一篇文章中,我们介绍了MongoDB.现在,我们来看下如何在MongoDB中进行常规的CRUD操作.毕竟,作为一个存储系统,它的基本功能就是对数据进行增删改查操作. MongoDB中的 ...
- 【Java EE 学习 44】【Hibernate学习第一天】【Hibernate对单表的CRUD操作】
一.Hibernate简介 1.hibernate是对jdbc的二次开发 2.jdbc没有缓存机制,但是hibernate有. 3.hibernate的有点和缺点 (1)优点:有缓存,而且是二级缓存: ...
- 使用MyBatis对表执行CRUD操作
一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0&quo ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis入门学习教程-使用MyBatis对表执行CRUD操作
上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...
随机推荐
- JDBC编程,从入门到精通
今天突然想多说两句,刚刚在知乎看到一个人说,在当今世界,没有技术型驱动的公司,全都是业务型.即便是表面上看似技术型公司,其本质还是为了服务业务.这段话推翻了我以前关于编程的所有看法,觉得颇有道理.下面 ...
- Hbase篇--Hbase和MapReduce结合Api
一.前述 Mapreduce可以自定义Inputforma对象和OutPutformat对象,所以原理上Mapreduce可以和任意输入源结合. 二.步骤 将结果写会到hbase中去. 2.1 Ma ...
- 甘果移动老甘:移动互联网变迁中的App和小程序
2018 年 10 月13 日,由又拍云和知晓云联合主办的 Open Talk 丨2018 小程序开发者沙龙系列活动广州站拉开帷幕,甘果移动的 CEO 路文杰(老甘)在沙龙上做了<移动互联网变迁 ...
- 网络协议 5 - ICMP 与 ping:投石问路的侦察兵
日常开发中,我们经常会碰到查询网络是否畅通以及域名对应 IP 地址等小需求,这时候用的最多的应该就是 ping 命令了. 那你知道 ping 命令是怎么工作的吗?今天,我们就来一起认识下 pi ...
- 【从零开始自制CPU之学习篇04】电容
电解电容: 多数在1μF以上,直接用数字表示.如:4.7μF.100μF.220μF等等.这种电容的两极有正负之分,长脚是正极. 独石电容: 独石电容器是多层陶瓷电容器的别称, 简称MLCC 读数方法 ...
- vue踩坑--TypeError: __WEBPACK_IMPORTED_MODULE_1_vuex__.a.store is not a constructor
今天在使用vuex的时候遇到这么个问题,虽然后来解决了,是首字母大写的原因,但我还是不知道为什么.这里先记录下来. 这是vuex/store.js import Vue from 'vue' impo ...
- C++可变参数模板实现输出
C++11 tuple&可变参数模板 template void Print(T value) { std::cout << value << std::endl; } ...
- iPhone多次输入错误密码锁机后刷机恢复(原有内容会丢失)
这个操作会完全丢失手机当前存储的资料,已经备份到iTunes的内容,将来可以通过iTunes恢复.已经被自动备份到iCloud的内容,比如通讯录,将来可以自动从iCloud恢复.以前没有备份过的资料, ...
- 如何使用Git提高研发团队工作效率?
为什么使用Git 随着互联网时代的来临与发展,尤其分布式开发的大力引入,对于开发工程师来说,代码管理变成了头等难题.10多个人或者更多的成员的研发团队如何管理同一份代码,异地办公如何跟同事有效的维护同 ...
- Zuul上实现限流(spring-cloud-zuul-ratelimit)
简述 Spring Cloud Zuul RateLimit项目Github地址: https://github.com/marcosbarbero/spring-cloud-zuul-ratelim ...