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

内容模块:

1:Java代码实现对数据库的增删查;

2:分页且获取页面信息;


这里针对于项目里面的Genre实体,以及对于它的操作进行举例

  1. package com.music.entity;
  2.  
  3. public class Genre {
  4. private int id;
  5. private String name;
  6. private String description;
  7.  
  8. public int getId() {
  9. return id;
  10. }
  11. public void setId(int id) {
  12. this.id = id;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public String getDescription() {
  21. return description;
  22. }
  23. public void setDescription(String description) {
  24. this.description = description;
  25. }
  26.  
  27. }

Genre.java

逻辑层代码展示:

GenreDao:

  1. package com.music.Dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.music.entity.Genre;
  6.  
  7. public interface GenreDao {
  8. //查询
  9. public List<Genre> getAll();
  10. //删除
  11. public boolean deleteGenre(int id);
  12. //插入
  13. public boolean addGenre(Genre g);
  14. //更新
  15. public boolean updateGenre(Genre g);
  16. }

在这个接口里方法的具体实现GenreDaoImpl:

  1. package com.music.Dao.Impl;
  2.  
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import com.music.Dao.GenreDao;
  9. import com.music.entity.Genre;
  10.  
  11. public class GenreDaoImpl extends BaseDao implements GenreDao{
  12.  
  13. //保存获取结果
  14. ArrayList<Genre> genres = new ArrayList<Genre>();
  15. @Override
  16. public List<Genre> getAll() {
  17. try {
  18. //创建连接
  19. openConnection();
  20. String sql = "select * from genre";
  21. //执行查询,获取结果
  22. ResultSet resultSet = executeQuery(sql, null);
  23. //将查询结果转换成对象
  24. while (resultSet.next()) {
  25. Genre g = new Genre();
  26. g.setId(resultSet.getInt("id"));
  27. g.setName(resultSet.getString("name"));
  28. g.setDescription(resultSet.getString("description"));
  29. genres.add(g);
  30. }
  31. } catch (ClassNotFoundException e) {
  32.  
  33. e.printStackTrace();
  34. } catch (SQLException e) {
  35.  
  36. e.printStackTrace();
  37. }finally{
  38. closeResourse();
  39. }
  40. return genres;
  41. }
  42.  
  43. @Override
  44. public boolean deleteGenre(int id) {
  45. boolean result = false;
  46. try {
  47. openConnection();
  48. String sql ="delete from genre where id = ?";
  49. result = excute(sql, new Object[]{id});
  50. } catch (ClassNotFoundException e) {
  51.  
  52. e.printStackTrace();
  53. } catch (SQLException e) {
  54.  
  55. e.printStackTrace();
  56. }finally{
  57. closeResourse();
  58. }
  59. return result;
  60. }
  61.  
  62. @Override
  63. public boolean addGenre(Genre g) {
  64. boolean result = false;
  65. try {
  66. openConnection();
  67. String sql ="insert into genre value(?,?,?)";
  68. result =excute(sql, new Object[]{
  69. g.getId(),
  70. g.getDescription(),
  71. g.getName()
  72. });
  73. } catch (ClassNotFoundException e) {
  74. e.printStackTrace();
  75. } catch (SQLException e) {
  76. e.printStackTrace();
  77. }finally{
  78. closeResourse();
  79. }
  80. return result;
  81. }
  82.  
  83. @Override
  84. public boolean updateGenre(Genre g) {
  85. boolean result = false;
  86. try {
  87. openConnection();
  88. String sql = "update genre set name = ?, description =? where id=?";
  89. result = excute(sql, new Object[]{
  90. g.getId()
  91. });
  92. } catch (ClassNotFoundException e) {
  93.  
  94. e.printStackTrace();
  95. } catch (SQLException e) {
  96.  
  97. e.printStackTrace();
  98. }finally{
  99. closeResourse();
  100. }
  101. return result;
  102.  
  103. }
  104.  
  105. public static void main(String[] args) {
  106. GenreDaoImpl genreDaoImpl = new GenreDaoImpl();
  107. genreDaoImpl.getAll();
  108. System.out.println(genreDaoImpl);
  109.  
  110. }
  111.  
  112. }

这里还必须要提出BaseDao:

  1. package com.music.Dao.Impl;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. public class BaseDao {
  10. //连接数据库
  11. private String className = "com.mysql.jdbc.Driver";
  12. private String dburl = "jdbc:mysql://localhost/ZJJ";
  13. private String user = "root";
  14. private String password = "root";
  15. private Connection connection;
  16. private PreparedStatement statement;
  17. private ResultSet resultSet;
  18.  
  19. public void openConnection() throws ClassNotFoundException, SQLException{
  20. //加载驱动
  21. Class.forName(className);
  22. //创建连接
  23. connection = DriverManager.getConnection(dburl,user,password);
  24. }
  25.  
  26. //查询方法
  27. public ResultSet executeQuery(String sql,Object[] params) throws SQLException{
  28. statement =connection.prepareStatement(sql);
  29. //追加参数
  30. if(params !=null){
  31. int i=1;
  32. for (Object object : params) {
  33. statement.setObject(i, object);
  34. i++;
  35. }
  36. }
  37. resultSet =statement.executeQuery();
  38. return resultSet;
  39. }
  40.  
  41. //更新
  42. public boolean excute(String sql,Object[] params) throws SQLException {
  43. statement =connection.prepareStatement(sql);
  44. if(params !=null){
  45. int i=1;
  46. for (Object object : params) {
  47. statement.setObject(i, object);
  48. }
  49. }
  50. return statement.execute();
  51. }
  52. //释放资源
  53. public void closeResourse(){
  54. try {
  55. if(resultSet != null){
  56. resultSet.close();
  57. }
  58. if(statement != null){
  59. statement.close();
  60. }
  61. if(connection != null){
  62. connection.close();
  63. }
  64.  
  65. } catch (SQLException e) {
  66. // TODO Auto-generated catch block
  67. e.printStackTrace();
  68. }
  69. }
  70.  
  71. }

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

今天报了一个错误:

错误的原因是:

这个setObject(i,object)有一个好处就是将所有的对象类型都写成object,这样就可以不用分开写各个类型的方法,比较简便。


分页:

接口部分:

  1. //分页
  2. public List<Album> getAlbumWithPage(int genreid,int pageNum,int pageSize);

1 public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize)

实现部分:

  1. public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize) {
  2. ArrayList<Album> albums = new ArrayList<Album>();
  3. //pageNum当前页数
  4. try {
  5. openConnection();
  6. String sql= "select * from album where genreid =? limit ?,?";
  7. ResultSet resultSet = executeQuery(sql, new Object[]{
  8. genreid,
  9. (pageNum-1)*pageSize,
  10. pageSize
  11. });
  12. while (resultSet.next()) {
  13. Album al= new Album();
  14. al.setId(resultSet.getInt("id"));
  15. al.setGenreid(resultSet.getInt("genreid"));
  16. al.setArtist(resultSet.getString("artist"));
  17. al.setTitle(resultSet.getString("title"));
  18. al.setPrice(resultSet.getBigDecimal("price"));
  19. al.setStock(resultSet.getInt("stock"));
  20. al.setDateReleased(resultSet.getString("dateReleased"));
  21. al.setDescription(resultSet.getString("description"));
  22. albums.add(al);
  23. }
  24. } catch (ClassNotFoundException e) {
  25.  
  26. e.printStackTrace();
  27. } catch (SQLException e) {
  28.  
  29. e.printStackTrace();
  30. }
  31. return albums;
  32.  
  1.  
  1. 1 public List<Album> getAlbumWithPage(int genreid, int pageNum, int pageSize) {

  1. return daoImpl.getAlbumWithPage(genreid, pageNum, pageSize);
  2. }
  3. @Override
  4. public int getRowCountWithGenreid(int id) {
  5. return daoImpl.getAlbumWithGenreid(id).size();
  6. }

JSP代码部分

  1. <%@page import="com.music.entity.Album"%>
  2. <%@page import="com.music.biz.Impl.AlbumBizImpl"%>
  3. <%@page import="com.music.biz.AlbumBiz"%>
  4. <%@page import="com.music.Dao.Impl.AlbumDaoImpl"%>
  5. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  7. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  8.  
  9. <html>
  10. <head>
  11. <title>欢迎光临 Music Store</title>
  12. <link type="text/css" rel="Stylesheet" href="style/front.css"/>
  13. <script type="text/javascript" src="script/jquery-1.4.1.js"></script>
  14. </head>
  15. <%
  16. AlbumBiz albumItem = new AlbumBizImpl();
  17. String id = request.getParameter("genreId");
  18.  
  19. int pageSize =3;
  20. int pageNum =1;
  21.  
  22. if(request.getParameter("page")!=null){
  23. pageNum =Integer.valueOf(request.getParameter("page"));
  24. }
  25.  
  26. List<Album> albums = albumItem.getAlbumWithPage(Integer.valueOf(id), pageNum, pageSize);
  27.  
  28. request.setAttribute("albums", albums);
  29. request.setAttribute("pageNum", pageNum);
  30.  
  31. int rows = albumItem.getRowCountWithGenreid(Integer.valueOf(id));
  32. int pageCount = (int)Math.ceil((double)rows/pageSize);
  33. // int pageCount =albumItem.getRowCountWithGenreid(Integer.valueOf(id));
  34. request.setAttribute("pageCount", pageCount);
  35.  
  36. request.setAttribute("genreId", id);
  37.  
  38. %>
  39.  
  40. <body>
  41. <div id="wrapper">
  42. <%@ include file="shared/front_header.jsp" %>
  43. <div id="content">
  44. <%@ include file="shared/front_sidebar.jsp" %>
  45. <div id="main">
  46. <h3 id="main-title">唱片列表</h3>
  47. <c:forEach var="album" items="${albums}">
  48. <table class="albumItem">
  49. <tr>
  50. <td rowspan="3" class="albumItem-image"><img src="CoverImages/${album.id}.jpg" alt="" /></td>
  51. <td colspan="2" class="albumItem-title">
  52. <a href="album.jsp?albumId=${album.id}">${album.title}</a>
  53. </td>
  54. </tr>
  55. <tr>
  56. <td class="albumItem-artist"><strong>歌手:${album.artist }</strong></td>
  57. <td class=".albumItem-price"><strong>定价:${album.price }</strong></td>
  58. </tr>
  59. <tr>
  60. <td colspan="2">
  61. ${album.description}
  62. </td>
  63. </tr>
  64. </table>
  65. </c:forEach>
  66. <hr/>
  67.  
  68. <a href="album_list.jsp?page=1&genreId=${genreId}&title=${title}">第一页</a>
  69. <c:if test="${pageNum>1 }">
  70. <a href="album_list.jsp?page=${pageNum-1}&genreId=${genreId}&title=${title}">上一页</a>
  71.  
  72. </c:if>
  73. <c:if test="${pageNum<pageCount}">
  74. <a href="album_list.jsp?page=${pageNum+1}&genreId=${genreId}&title=${title}">下一页</a>
  75. </c:if>
  76. <a href="album_list.jsp?page=${pageCount}&genreId=${genreId}&title=${title}">最后一页</a>
  77. &nbsp;共${pageCount}页,第${pageNum}页。
  78.  
  79. </div>
  80. <div class="clearBoth"></div>
  81. </div>
  82. <%@ include file="shared/front_footer.jsp" %>
  83. </div>
  84. </body>
  85. </html>

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

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

Java代码实现 增删查 + 分页——实习第四天的更多相关文章

  1. java中CRUD(增删查改)底层代码的实现

    java中CRUD(增删查改)底层代码的实现: package com.station.dao; import com.station.model.Product; import java.sql.* ...

  2. MongoDB在Java下的增删查改

    我们总不能一直使用cmd对数据库操作,数据库总是要在程序中使用的.今天来说一下怎么通过Java调用MongoDB. 学习一下最基本也是最常用的增删查改语句,这是使用数据库的基础. 注意事项: 1.要打 ...

  3. node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)

    最近写了一个用node来操作MongoDB完成增.删.改.查.排序.分页功能的示例,并且已经放在了服务器上地址:http://39.105.32.180:3333. Mongoose是在node.js ...

  4. Java连接MySQL数据库及简单的增删查改操作

    主要摘自 https://www.cnblogs.com/town123/p/8336244.html https://www.runoob.com/java/java-mysql-connect.h ...

  5. JAVA原生mvc实现用户信息的增删查改

    笔者最近学完jsp和servlet,于是心血来潮的打算写个简单的用户案例 环境准备: 开发工具eclipse jdk-1.8.0_72 tomcat-9.0.5 前端部分: 1.自己手写了一套样式 2 ...

  6. 后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)

    1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...

  7. SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)

    SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)-DML 1.SQL INSERT INTO 语句(在表中插入) INSERT INTO 语句用于向表中插入新记录. SQL I ...

  8. SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码)

    SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码) 概述: 表由行和列组成,每个表都必须有个表名. SQL CREATE TABLE 语法 CREATE TABLE tabl ...

  9. 分享一段ios数据库代码,包括对表的创建、升级、增删查改

    分享一段ios数据库代码.包括创建.升级.增删查改. 里面的那些类不必细究,主要是数据库的代码100%可用. 数据库升级部分,使用switch,没有break,低版本一次向高版本修改. // DB.h ...

随机推荐

  1. Oracle GoldenGate中HANDLECOLLISIONS参数使用详解

    Oracle GoldenGate中HANDLECOLLISIONS参数使用详解   HANDLECOLLISIONS 是一个 replicat 进程参数,主要在 initial load 中使用.在 ...

  2. 最简单的html5语言

    什么是 HTML5? HTML5 是下一代 HTML 标准. 最小的HTML5文档 下面是一个简单的HTML5文档: <</span>!DOCTYPE html><< ...

  3. 微软Build 2017第二天 .NET Standard 2.0 Preview 的客户端跨平台

    微软公司一年一度的开发者大会,即“Microsoft Build 2017”在总部西雅图正式开幕.按照官方安排,本次大会将持续 3 天,主题围绕微软公司各项最新技术成果的展示和研讨,包括与微软相关的产 ...

  4. 最常用的缓存技术---redis入门

      Redis简介 Redis是基于内存,也可以基于磁盘持久化nosql数据库,使用c语言开发. 数据存储结构:key-value 安装环境准备 Redis使用c语言开发,需要使用gcc编译程序进行编 ...

  5. Natas Wargame Level 3 Writeup 与 robots.txt

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnsAAAC5CAYAAABQi/kBAAAABHNCSVQICAgIfAhkiAAAIABJREFUeF

  6. HTM CSS 笔记乱炖

    一.常用实体(字符转义) '<' == '<' '©' == '©' '>' == '>' '"' == '"' ' ' == ' ' '®' == '®' ...

  7. 017 多对多关联映射 双向(many-to-many)

    多对多关联映射 双向 两方都持有对象引用,修改对象模型,但数据的存储没有变化. 再修改映射文件: public class Role { private int id; private String ...

  8. zabbix server安装详解

    简介 zabbix(音同 zæbix)是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案. zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以 ...

  9. Redis 小白指南(四)- 数据的持久化保存(草稿)

    Redis 小白指南(四)- 数据的持久化保存 简介 因为 redis 将数据保存在内存中,很容易诱发的一个问题就是,程序崩溃或服务器重启等情况如何保证数据的正常存储. 当我们以 redis 作为主数 ...

  10. STL语法——映射:map 反片语(Ananagrams,UVa 156)

    Description Most crossword puzzle fans are used to anagrams--groups of words with the same letters i ...