Java代码实现 增删查 + 分页——实习第四天
今天项目内容已经开始了,并且已经完成好多基本操作,今天就开始总结今天学习到的内容,和我遇到的问题,以及分析这其中的原因。
内容模块:
1:Java代码实现对数据库的增删查;
2:分页且获取页面信息;
这里针对于项目里面的Genre实体,以及对于它的操作进行举例
package com.music.entity; public class Genre {
private int id;
private String name;
private String description; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} }
Genre.java
逻辑层代码展示:
GenreDao:
package com.music.Dao; import java.util.List; import com.music.entity.Genre; public interface GenreDao {
//查询
public List<Genre> getAll();
//删除
public boolean deleteGenre(int id);
//插入
public boolean addGenre(Genre g);
//更新
public boolean updateGenre(Genre g);
}
在这个接口里方法的具体实现GenreDaoImpl:
package com.music.Dao.Impl; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.music.Dao.GenreDao;
import com.music.entity.Genre; public class GenreDaoImpl extends BaseDao implements GenreDao{ //保存获取结果
ArrayList<Genre> genres = new ArrayList<Genre>();
@Override
public List<Genre> getAll() {
try {
//创建连接
openConnection();
String sql = "select * from genre";
//执行查询,获取结果
ResultSet resultSet = executeQuery(sql, null);
//将查询结果转换成对象
while (resultSet.next()) {
Genre g = new Genre();
g.setId(resultSet.getInt("id"));
g.setName(resultSet.getString("name"));
g.setDescription(resultSet.getString("description"));
genres.add(g);
}
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) { e.printStackTrace();
}finally{
closeResourse();
}
return genres;
} @Override
public boolean deleteGenre(int id) {
boolean result = false;
try {
openConnection();
String sql ="delete from genre where id = ?";
result = excute(sql, new Object[]{id});
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) { e.printStackTrace();
}finally{
closeResourse();
}
return result;
} @Override
public boolean addGenre(Genre g) {
boolean result = false;
try {
openConnection();
String sql ="insert into genre value(?,?,?)";
result =excute(sql, new Object[]{
g.getId(),
g.getDescription(),
g.getName()
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeResourse();
}
return result;
} @Override
public boolean updateGenre(Genre g) {
boolean result = false;
try {
openConnection();
String sql = "update genre set name = ?, description =? where id=?";
result = excute(sql, new Object[]{
g.getId()
});
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) { e.printStackTrace();
}finally{
closeResourse();
}
return result; } public static void main(String[] args) {
GenreDaoImpl genreDaoImpl = new GenreDaoImpl();
genreDaoImpl.getAll();
System.out.println(genreDaoImpl); } }
这里还必须要提出BaseDao:
package com.music.Dao.Impl; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class BaseDao {
//连接数据库
private String className = "com.mysql.jdbc.Driver";
private String dburl = "jdbc:mysql://localhost/ZJJ";
private String user = "root";
private String password = "root";
private Connection connection;
private PreparedStatement statement;
private ResultSet resultSet; public void openConnection() throws ClassNotFoundException, SQLException{
//加载驱动
Class.forName(className);
//创建连接
connection = DriverManager.getConnection(dburl,user,password);
} //查询方法
public ResultSet executeQuery(String sql,Object[] params) throws SQLException{
statement =connection.prepareStatement(sql);
//追加参数
if(params !=null){
int i=1;
for (Object object : params) {
statement.setObject(i, object);
i++;
}
}
resultSet =statement.executeQuery();
return resultSet;
} //更新
public boolean excute(String sql,Object[] params) throws SQLException {
statement =connection.prepareStatement(sql);
if(params !=null){
int i=1;
for (Object object : params) {
statement.setObject(i, object);
}
}
return statement.execute();
}
//释放资源
public void closeResourse(){
try {
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
这个里面的方法都会获得调用。
今天报了一个错误:
错误的原因是:
这个setObject(i,object)有一个好处就是将所有的对象类型都写成object,这样就可以不用分开写各个类型的方法,比较简便。
分页:
接口部分:
//分页
public List<Album> getAlbumWithPage(int genreid,int pageNum,int pageSize);
1 public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize)
实现部分:
public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize) {
ArrayList<Album> albums = new ArrayList<Album>();
//pageNum当前页数
try {
openConnection();
String sql= "select * from album where genreid =? limit ?,?";
ResultSet resultSet = executeQuery(sql, new Object[]{
genreid,
(pageNum-1)*pageSize,
pageSize
});
while (resultSet.next()) {
Album al= new Album();
al.setId(resultSet.getInt("id"));
al.setGenreid(resultSet.getInt("genreid"));
al.setArtist(resultSet.getString("artist"));
al.setTitle(resultSet.getString("title"));
al.setPrice(resultSet.getBigDecimal("price"));
al.setStock(resultSet.getInt("stock"));
al.setDateReleased(resultSet.getString("dateReleased"));
al.setDescription(resultSet.getString("description"));
albums.add(al);
}
} catch (ClassNotFoundException e) { e.printStackTrace();
} catch (SQLException e) { e.printStackTrace();
}
return albums;
1 public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize) {
return daoImpl.getAlbumWithPage(genreid, pageNum, pageSize);
} @Override
public int getRowCountWithGenreid(int id) { return daoImpl.getAlbumWithGenreid(id).size();
}
JSP代码部分
<%@page import="com.music.entity.Album"%>
<%@page import="com.music.biz.Impl.AlbumBizImpl"%>
<%@page import="com.music.biz.AlbumBiz"%>
<%@page import="com.music.Dao.Impl.AlbumDaoImpl"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html>
<head>
<title>欢迎光临 Music Store</title>
<link type="text/css" rel="Stylesheet" href="style/front.css"/>
<script type="text/javascript" src="script/jquery-1.4.1.js"></script>
</head>
<%
AlbumBiz albumItem = new AlbumBizImpl();
String id = request.getParameter("genreId"); int pageSize =3;
int pageNum =1; if(request.getParameter("page")!=null){
pageNum =Integer.valueOf(request.getParameter("page"));
} List<Album> albums = albumItem.getAlbumWithPage(Integer.valueOf(id), pageNum, pageSize); request.setAttribute("albums", albums);
request.setAttribute("pageNum", pageNum); int rows = albumItem.getRowCountWithGenreid(Integer.valueOf(id));
int pageCount = (int)Math.ceil((double)rows/pageSize);
// int pageCount =albumItem.getRowCountWithGenreid(Integer.valueOf(id));
request.setAttribute("pageCount", pageCount); request.setAttribute("genreId", id); %> <body>
<div id="wrapper">
<%@ include file="shared/front_header.jsp" %>
<div id="content">
<%@ include file="shared/front_sidebar.jsp" %>
<div id="main">
<h3 id="main-title">唱片列表</h3>
<c:forEach var="album" items="${albums}">
<table class="albumItem">
<tr>
<td rowspan="3" class="albumItem-image"><img src="CoverImages/${album.id}.jpg" alt="" /></td>
<td colspan="2" class="albumItem-title">
<a href="album.jsp?albumId=${album.id}">${album.title}</a>
</td>
</tr>
<tr>
<td class="albumItem-artist"><strong>歌手:${album.artist }</strong></td>
<td class=".albumItem-price"><strong>定价:${album.price }</strong>¥</td>
</tr>
<tr>
<td colspan="2">
${album.description}
</td>
</tr>
</table>
</c:forEach>
<hr/> <a href="album_list.jsp?page=1&genreId=${genreId}&title=${title}">第一页</a>
<c:if test="${pageNum>1 }">
<a href="album_list.jsp?page=${pageNum-1}&genreId=${genreId}&title=${title}">上一页</a> </c:if>
<c:if test="${pageNum<pageCount}">
<a href="album_list.jsp?page=${pageNum+1}&genreId=${genreId}&title=${title}">下一页</a>
</c:if>
<a href="album_list.jsp?page=${pageCount}&genreId=${genreId}&title=${title}">最后一页</a>
共${pageCount}页,第${pageNum}页。 </div>
<div class="clearBoth"></div>
</div>
<%@ include file="shared/front_footer.jsp" %>
</div>
</body>
</html>
对于分页,前面的博客有讲述,就不赘述了~
说实话,今天我好累了~就写那么多吧~现在距离下课还有5分钟,我要记会儿单词~
Java代码实现 增删查 + 分页——实习第四天的更多相关文章
- java中CRUD(增删查改)底层代码的实现
java中CRUD(增删查改)底层代码的实现: package com.station.dao; import com.station.model.Product; import java.sql.* ...
- MongoDB在Java下的增删查改
我们总不能一直使用cmd对数据库操作,数据库总是要在程序中使用的.今天来说一下怎么通过Java调用MongoDB. 学习一下最基本也是最常用的增删查改语句,这是使用数据库的基础. 注意事项: 1.要打 ...
- node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)
最近写了一个用node来操作MongoDB完成增.删.改.查.排序.分页功能的示例,并且已经放在了服务器上地址:http://39.105.32.180:3333. Mongoose是在node.js ...
- Java连接MySQL数据库及简单的增删查改操作
主要摘自 https://www.cnblogs.com/town123/p/8336244.html https://www.runoob.com/java/java-mysql-connect.h ...
- JAVA原生mvc实现用户信息的增删查改
笔者最近学完jsp和servlet,于是心血来潮的打算写个简单的用户案例 环境准备: 开发工具eclipse jdk-1.8.0_72 tomcat-9.0.5 前端部分: 1.自己手写了一套样式 2 ...
- 后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)
1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...
- SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)
SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)-DML 1.SQL INSERT INTO 语句(在表中插入) INSERT INTO 语句用于向表中插入新记录. SQL I ...
- SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码)
SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码) 概述: 表由行和列组成,每个表都必须有个表名. SQL CREATE TABLE 语法 CREATE TABLE tabl ...
- 分享一段ios数据库代码,包括对表的创建、升级、增删查改
分享一段ios数据库代码.包括创建.升级.增删查改. 里面的那些类不必细究,主要是数据库的代码100%可用. 数据库升级部分,使用switch,没有break,低版本一次向高版本修改. // DB.h ...
随机推荐
- SQL中LEFT JOIN 和 inner join 的区别
student表 sc 表 首先where条件a.Sid = b.Sid 查询 SELECT * FROM student a,sc b WHERE a.Sid = b.Sid GROUP BY a. ...
- hdu3709 Balanced Number 数位DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3709 题目大意就是求给定区间内的平衡数的个数 要明白一点:对于一个给定的数,假设其位数为n,那么可以有 ...
- Java实现八种排序算法(代码详细解释)
经过一个多星期的学习.收集.整理,又对数据结构的八大排序算法进行了一个回顾,在测试过程中也遇到了很多问题,解决了很多问题.代码全都是经过小弟运行的,如果有问题,希望能给小弟提出来,共同进步. 参考:数 ...
- selenium基础框架的封装(Python版)
一.常用函数的封装 在使用selenium做web自动化测试的过程中,经常会碰到各种各样的问题,比如: 1.页面加载比较慢时,selenium查找元素抛出异常,导致脚本运行中止 2.写完脚本后发现代码 ...
- RecyclerView添加头部和底部视图的实现方法
引用-- http://www.zhimengzhe.com/Androidkaifa/15072.html 在天下货crm----签到---签到记录中有使用
- 通过rpm 安装MYSQL
1.MYSQL Server端安装: 2.MYSQL client 安装 3.设置MYSQL密码(安装了MySql客户端才可以执行) ' 4.登录MYSQL mysql 的最简单的安装方法啦
- 互联网二次进化—VR全景智慧城市
vr全景智慧城市被称为中国首家商业全景平台.VR被称为下一代超级人机交互平台. 时间往前推20年,1996年,电脑还是很新鲜的玩意儿.那时,我第一次接触电脑,在我父亲供职的单位,一个开着空调的房间里, ...
- 软件工程期末考试 AHNU
1. 数据流图:一种图形化技术,它描绘信息流和数据从输入移动到输出的过程中所经受的变换.在数据流图中没有任何具体的物理部件,它只是描绘数据在软件中流动和被处理的逻辑过程,是系统逻辑功能的图形 ...
- oracle数据库常用的99条查询语句(转载)
1. select * from emp; 2. select empno, ename, job from emp; 3. select empno 编号, ename 姓名, job 工作 fro ...
- Nginx教程(四) Location配置与ReWrite语法
Nginx教程(四) Location配置与ReWrite语法 1 Location语法规则 1.1 Location规则 语法规则: location [=|~|~*|^~] /uri/ {- } ...