Java代码实现 增删查 + 分页——实习第四天

时间:2023-01-17 14:40:31

今天项目内容已经开始了,并且已经完成好多基本操作,今天就开始总结今天学习到的内容,和我遇到的问题,以及分析这其中的原因。

内容模块:

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

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();
}
} }

这个里面的方法都会获得调用。

今天报了一个错误:

Java代码实现 增删查 + 分页——实习第四天

错误的原因是:

Java代码实现 增删查 + 分页——实习第四天

这个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>
&nbsp;共${pageCount}页,第${pageNum}页。 </div>
<div class="clearBoth"></div>
</div>
<%@ include file="shared/front_footer.jsp" %>
</div>
</body>
</html>

对于分页,前面的博客有讲述,就不赘述了~

说实话,今天我好累了~就写那么多吧~现在距离下课还有5分钟,我要记会儿单词~