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 ...
随机推荐
- 关于echarts的那些事(地图标点,折线图,饼图)
前记:离上一篇博客的发布已经过去两个月了,这期间总想写点什么,却怎么都写不出来,一直拖到了现在.现在的感觉,不是像这期间一样,想好好整理一番,写一篇好博客,却写不出来.事实发现,随心就好,较好的博客, ...
- ArcGIS 网络分析[2] 利用自定义基础数据创建网络数据集
前言 似乎除了官方介绍的例子,我还没有在网上见过一篇介绍如何"使用自己的数据"创建"网络数据集"的文章. 有介绍几何网络的,有介绍如何用官方SanFrancis ...
- 设置共享目录(主机win7,虚拟机Ubuntu)
1.安装增强功能包 启动虚拟机后,在 设备 -> 分配光驱 选择VBoxGuestAdditions.iso增强包镜像(在virtualbox安装目录下) 在虚拟机中挂载光驱镜像: #mkdir ...
- Thinkphp3.2———配置模块
一.配置格式 Thinkphp框架中的所有配置都是数组形式定义的的格式为: //项目配置 return array( 'DEFAULT_MODULE'=>'Index',//默认模块 'URL_ ...
- MySQL ProxySQL读写分离实践
目的 在上一篇文章MySQL ProxySQL读写分离使用初探里初步介绍了ProxySQL的使用,本文继续介绍它的一些特点和DBProxy的性能差异.深入一些去了解ProxySQL,通过测试来说明Pr ...
- 为什么非全站升级HTTPS不可?
升级HTTPS已经是大势所趋,但仍有大量互联网企业犹豫是否要全站升级HTTPS,为此本文梳理了全站升级HTTPS与部分升级HTTPS的优劣势对比,来判断是否真的有必要进行全站HTTPS升级. HTTP ...
- Git Flow Note
近期困惑于Git代码版本控制,集中两天时间研究,其中基础知识来源于<Git权威指南>,分支思想则来源于一篇博文<A successful Git branching model> ...
- Visual Studio2017中如何让Entity Framework工具【ADO.NET实体数据模型】支持MYSQL数据源
熟悉Entity Framework应该对以下图片不陌生,他就是ADO.NET实体数据模型向导:可以将数据库的表自动生成模型类,或者创建Code First的模型文件. 但是这个模型向导默认只显示微软 ...
- XML文件生成——借助JDOM
import java.io.* ; import org.jdom.* ; import org.jdom.output.* ; public class DOMDemo { public stat ...
- ehcache-----在spring和hibernate下管理ehcache和query cache
1. 在Hibernate配置文件中设置: <!-- Hibernate SessionFactory --> <bean id="sessionFactory" ...