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 ...
随机推荐
- hdu2059 龟兔赛跑 DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2059 虽然 知道是DP ,刚开始一直没有想出状态转移方程. 刚开始的思路就是定义dp[i]表示到达第i ...
- Linux系统档案与文件系统的压缩与打包
以下文章基于centos6.5 文章引自:http://www.jb51.net/LINUXjishu/105916.html 一.Linux下常见的压缩指令 在linux的环境中,压缩文件的扩展名大 ...
- hive网站日志数据分析
一.说在前面的话 上一篇,楼主介绍了使用flume集群来模拟网站产生的日志数据收集到hdfs.但我们所采集的日志数据是不规则的,同时也包含了许多无用的日志.当需要分析一些核心指标来满足系统业务决策的时 ...
- 使用FileSystem自带的api读取hdfs中的文件
博客搬家自https://my.oschina.net/itsyizu/blog/ 1. 创建hadoop MapReduce项目 输入项目名称 创建好的项目初始化状态如下 编写java类 impor ...
- StringBuffer类的使用
//简单记录下Java中StringBuffer类的基本功能使用public class Test01{ public static void main(String[] args){ //New一个 ...
- 微信小程序大全(上)(最新整理 建议收藏)
- Git简略教程
Git使用教程 厂里大部分后端应用的版本控制工具为SVN,前端代码则更习惯于Git,好久不用Git有些生疏,复习一下,效率就是生命. 1.拉取远程分支到本地 git clone + 代码地址 + 分支 ...
- vue-动手做个选择城市
查看完整的代码请到 我的github地址 https://github.com/qianyinghuanmie/vue2.0-demos 一.结果展示 二.前期准备: 1.引入汉字转拼音的插件, ...
- LINQ基础(三)
一.并行LINQ System.Linq名称空间中包含的类ParallelEnumerable可以分解查询的工作,使其分布在多个线程上. 尽管Enumerable类给IEnumerable<T& ...
- source install sshpass in aix
1.源码下载: wget https://nchc.dl.sourceforge.net/project/sshpass/sshpass/1.06/sshpass-1.06.tar.gz 2.解压 ...