使用JSP+SERVLET+JDBC实现对数据库的增删改查
JSP的网络数据库连接技术及运用之研究

JSP的网络数据库连接技术及运用之研究JSP技术已经成为了Web应用程序中最广泛使用的技术之一。
而网络数据库连接则是JSP技术中使用最广泛的技术之一。
本文将会探讨JSP技术中网络数据库连接技术的相关内容,同时也会介绍其如何应用于实际项目中。
一、JSP技术概述JSP,即Java Server Pages,它是Sun Microsystems为了简化网站开发而开发的一套技术方案。
JSP技术通过将Java代码嵌入到HTML页面中来实现页面的动态性,同时通过Java Servlet技术来实现Web应用程序的逻辑控制。
JSP技术具有以下优点:1、易于维护:由于JSP技术将Java代码嵌入到HTML页面中,因此页面开发的工作变得更加容易,并且这种技术也使得页面的维护非常方便。
2、灵活性高:JSP技术可以支持Java的强大功能,不仅可以方便地进行页面的开发和维护,还可以很方便地对程序进行扩展。
3、高性能:与ASP、PHP等页面开发技术相比,JSP技术的性能非常高,这也是其在大型网站中得以广泛使用的原因之一。
二、网络数据库连接技术网络数据库连接技术是JSP技术中使用最为广泛的技术之一。
该技术通常使用Java数据库连接(JDBC)技术来实现。
JDBC是Java语言中用于与关系型数据库进行通信的标准API。
通过JDBC技术,JSP开发人员可以完成对数据库的增删改查等操作。
JDBC技术的核心是数据库驱动程序(driver),驱动程序是一个Java库,使得JDBC 可以与各种数据库进行交互。
驱动程序分为两种类型:JDBC-ODBC桥接器(Bridge)和纯Java驱动程序。
JDBC-ODBC桥接器在JDK 8中已被弃用,因此现在的Java应用程序中通常使用纯Java驱动程序。
常见的数据库驱动程序有以下几种:1、Oracle数据库驱动程序(OracleDriver)。
2、MySQL数据库驱动程序(com.mysql.jdbc.Driver)。
用jsp程序对数据库表进行增、删、差、改操作

pstmt.setString(6,request.getParameter("Phone")) ;
pstmt.setFloat(7,Float.parseFloat(Grade)) ;//这个地方的问题要牢记
pstmt.setFloat(8,Float.parseFloat(Use)) ;//这个地方的问题要牢记
生 日 费:<input type="text"name="Use"><br>
<input type="submit"value="添加">
<input type="reset"value="重置">
</font>
</form>
<h3><a href="admin.jsp">返回</a>管理员页面</h3>
int x = pstmt.executeUpdate() ;//这个用法牢记
%>
<%
if(x>=1){
flag = true;
%>
添加信息成功!
<h3><a href="admin.jsp">返回</a>管理员页面</h3>
<%
}
%>
<%
}catch(Exception e){
e.printStackTrace() ;
Servlet实现增删改查功能

MVC模式M:Model,即模型,对于JavaBeanV:View,即试图,对应JSP页面C:Controller,即控制器,对应Servlet1.以下为MVC实现一个简单的增删改查功能1>显示记录2>增加一条记录3>修改一条记录4>删除一条记录程序源代码:M层:模型层1.封装一条信息的所有属性JavaBean.java ,即VO package muta.bean;/*** @author help*封装一条信息的所有属性*/public class JavaBean {private int id;private String name;private String password;private String sex;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getPassword() {return password;}public void setPassword(String password) { this.password = password;}public String getSex() {return sex;}public void setSex(String sex) {/*** @author help*操作数据库的方法*/public class SqlBean {Connection con;PreparedStatement pre;ResultSet rs;public SqlBean(){try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}try {con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/MyServl et","root","122828");} catch (SQLException e) {e.printStackTrace();}}/*** @author help**插入新的一条记录* @return*/public int getInsert(String sql,JavaBean jBean) {int count =0;try {pre = con.prepareStatement(sql);pre.setString(1,jBean.getName());pre.setString(2,jBean.getPassword());pre.setString(3,jBean.getSex());pre.setInt(4,jBean.getAge());count=pre.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}/*** @author help**删除一条记录* @return*/public int getDelete(String sql,int id){int count =0;try {pre = con.prepareStatement(sql);pre.setInt(1, id);count=pre.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}/*** @author help**根据ID查询某一条记录* @return*/public JavaBean getSearchById(String sql,int id){JavaBean jBean = new JavaBean();try {pre = con.prepareStatement(sql);pre.setInt(1, id);rs=pre.executeQuery();while(rs.next()){jBean.setId(rs.getInt("id"));jBean.setName(rs.getString("name"));jBean.setPassword(rs.getString("password"));jBean.setSex(rs.getString("sex"));jBean.setAge(rs.getInt("age"));}} catch (SQLException e){e.printStackTrace();}return jBean;}/*** @author help**更新某一条记录* @return*/public int getUpdate(String sql,JavaBean jBean) {int count =0;try {pre = con.prepareStatement(sql);pre.setInt(5,jBean.getId());pre.setString(1,jBean.getName());pre.setString(2,jBean.getPassword());pre.setString(3,jBean.getSex());pre.setInt(4,jBean.getAge());count = pre.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}jBean.setAge(rs.getInt("age"));list.add(jBean);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return list;}}V层:试图层1.显示记录集的页面 SearchList.jsp<%@page language="java"import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>显示记录</title></head><body><center><font color=red size=72>学生信息如下:</font><hr><table border=1bgColor="#ffffff"width="500px" height="100px"><tr><td>ID</td><td>姓名</td><td>密码</td><td>性别</td><td>年龄</td><td><center>操作</center></td></tr><jsp:useBean id="sBean"class="muta.bean.SqlBean"/> <jsp:useBean id="jBean"class="muta.bean.JavaBean"/><%String sql ="select * from student order by id";java.util.List list =sBean.getSearch(sql);for(java.util.Iterator it=list.iterator();it.hasNext();){//获取一个JavaBean对象jBean =(muta.bean.JavaBean)it.next();%><tr><td><%=jBean.getId() %></td><td><%=jBean.getName() %></td><td><%=jBean.getPassword() %></td><td><%=jBean.getSex() %></td><td><%=jBean.getAge() %></td><td><a href="Insert.jsp">增加</a><a href="Delete?id=<%=jBean.getId()%>">删除</a> <ahref="SearchById?id=<%=jBean.getId()%>">更新</a> </td></tr><% }%></table>2.插入页面Insert.jsp<center><font color=red size=72>学生管理页面</font><hr><form action="Insert"method="post"><table border="1"><tr><td>姓名:</td><td><input name ="name"></td></tr><tr><td>密码:</td><td><input type="password"name ="password"></td> </tr><tr><td>性别:</td><td><input type="radio"name ="sex"value="男">男<input type="radio"name ="sex"value="女">女</td><tr><td>年龄:</td><td><input type="text"name ="age"></td> </tr><tr><td colspan="2"><center><input type="submit"value="提交"><input type="reset"value="重置"></center></td></tr></table></form><a href="SearchList.jsp">查询</a></center></body></html>3.更新页面Update.jsp<%@page language="java"import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>更新</title></head><body><center><font color=red size=72>学生管理页面</font><hr><form action="Update"method="post""><table border="1"><tr><td>学生ID:</td><td><input name="id"value="<%=request.getAttribute("id") %>" readonly></td></tr><tr><td>学生姓名:</td><td><input name="name"value="<%=request.getAttribute("name") %>"></td> </tr><tr><td>学生密码:</td><td><input type="password"name="password"value="<%=request.getAttribute("password") %>"> </td></tr><tr><td>学生性别:</td><td><input type="radio"name ="sex"value="男"<%=request.getAttribute("man") %>>男<input type="radio"name ="sex"value="女"<%=request.getAttribute("woman") %>>女</td></tr><tr><td>学生年龄:</td><td><input type="text"name="age"value="<%=request.getAttribute("age") %>"></td> </tr><tr><td colspan="2"><center><input type="submit"value="提交"><input type="reset"value="重置"></center>4.出错页面Error.jspC层:控制层—Servlet1.显示记录集的Servlet----SearchById.javapackage muta.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import muta.bean.JavaBean;import muta.bean.SqlBean;public class SearchById extends HttpServlet {private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponseresponse)throws ServletException, IOException {doPost(request,response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");//获取用户IDString sid = request.getParameter("id");int id =Integer.parseInt(sid);String sql ="select * from student where id=?"; SqlBean sBean = new SqlBean();JavaBean jBean = sBean.getSearchById(sql, id);//用户IDrequest.setAttribute("id",jBean.getId());//用户姓名request.setAttribute("name",jBean.getName());//用户密码request.setAttribute("password",jBean.getPassword());//用户性别String sex="";String man="";String woman="";if(jBean.getSex()!=null){sex=jBean.getSex().trim();if(sex.equals("男")){man ="checked";}else{woman ="checked";}}request.setAttribute("man",man);request.setAttribute("woman",woman);//用户年龄request.setAttribute("age",jBean.getAge());//转发request.getRequestDispatcher("Update.jsp").forward(request,2.增加记录的Servlet----Insert.javaprivate static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @param request the request send by the client to the server* @param response the response send by the server to the client * @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");doPost(request,response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获取前台页面数据String name =request.getParameter("name");String password =request.getParameter("password");String sex =request.getParameter("sex");String sage = request.getParameter("age");int age =Integer.parseInt(sage);//封装到JavaBean对象中去JavaBean jBean = new JavaBean();jBean.setName(name);jBean.setPassword(password);jBean.setSex(sex);jBean.setAge(age);//调用模型层String sql = "insert into student(name,password,sex,age) values(?,?,?,?)";SqlBean sBean = new SqlBean();int count =sBean.getInsert(sql,jBean);String url="";if(count>0){url="SearchList.jsp";}else{url ="error.jsp";request.setAttribute("error", "ע��");}//转发ת3.更新记录的Servlet----Updated.java/****/private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @param request the request send by the client to the server* @param response the response send by the server to the client * @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获得前台表单信息String sid = request.getParameter("id");int id =Integer.parseInt(sid);String name =request.getParameter("name");String password =request.getParameter("password");String sex =request.getParameter("sex");String sage = request.getParameter("age");int age =Integer.parseInt(sage);//封装到JavaBean对象中去JavaBean jBean = new JavaBean();jBean.setId(id);jBean.setName(name);jBean.setPassword(password);jBean.setSex(sex);jBean.setAge(age);String sql ="update student set name=?,password=?,sex=?,age=? where id=?";SqlBean sBean = new SqlBean();int count =sBean.getUpdate(sql,jBean);String url="";if(count>0){url="SearchList.jsp";}4.删除记录的Servlet----Delete.javaimport muta.bean.SqlBean;public class Delete extends HttpServlet {private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @param request the request send by the client to the server* @param response the response send by the server to the client * @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");doPost(request,response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals topost.** @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");//获取超链接传来的数据String sId = request.getParameter("id");int id =Integer.parseInt(sId);////调用模型层删除方法String sql = "delete from student where id=?";SqlBean sBean = new SqlBean();int count =sBean.getDelete(sql, id);XML文件xsi:schemaLocation="/xml/ns /javaee/xml/ns/javaee/web-app_2_5. xsd"><servlet><servlet-name>Update</servlet-name><servlet-class>muta.servlet.Update</servlet-class ></servlet><servlet><servlet-name>SearchById</servlet-name><servlet-class>muta.servlet.SearchById</servlet-c lass></servlet><servlet><servlet-name>Insert</servlet-name><servlet-class>muta.servlet.Insert</servlet-class ></servlet><servlet><servlet-name>Delete</servlet-name><servlet-class>muta.servlet.Delete</servlet-class ></servlet><servlet-mapping><servlet-name>Update</servlet-name><url-pattern>/Update</url-pattern></servlet-mapping><servlet-mapping><servlet-name>SearchById</servlet-name><url-pattern>/SearchById</url-pattern></servlet-mapping><servlet-mapping><servlet-name>Insert</servlet-name><url-pattern>/Insert</url-pattern></servlet-mapping>。
使用JSP对数据库进行增删改查

使用JSP对数据库进行增删改查JSP(Java Server Pages)是一种用于开发Web应用程序的Java技术。
它可以直接在HTML页面中嵌入Java代码,实现动态生成页面内容。
在使用JSP进行数据库的增删改查操作时,通常需要借助JDBC(Java Database Connectivity)来进行数据库的连接和操作。
接下来,需要进行数据库的连接。
可以使用JDBC提供的DriverManager类和Connection接口来实现。
首先,需要定义数据库的相关信息,如驱动程序名称、数据库URL、用户名和密码。
然后,使用DriverManager的静态方法getConnection(来获取数据库连接,传入相应的参数。
例如,对于MySQL数据库,可以使用如下代码进行连接:String url = "jdbc:mysql://localhost:3306/database_name"; // 数据库URLString userName = "root"; // 数据库用户名String password = "password"; // 数据库密码try//加载驱动程序Class.forName(driverName);//获取数据库连接Connection connection = DriverManager.getConnection(url, userName, password);//...} catch (ClassNotFoundException e)e.printStackTrace(;} catch (SQLException e)e.printStackTrace(;连接成功后,接下来可以进行数据库的增删改查操作。
通常,可以使用JDBC的Statement或PreparedStatement对象来执行SQL语句。
Statement对象用于静态SQL语句,而PreparedStatement对象用于动态SQL语句。
实验报告模版

《软件开发架构平台技术》课程实验报告报告人:班级:指导老师:实验一XML与DOM实例编程一、实验目的熟悉XML技术,使用CSS技术和XSLT对XML文档进行格式化,熟练使用DOM技术来对XML进行解析。
二、实验内容写上孔老师要求作的内容三、实验步骤写上各自完成实验的步骤四、实验源代码及输出实验二JDBC实例开发一、实验目的熟悉JDBC常用类,复习SQL语句,使用SQL语句和JDBC来实现对数据库进行增删改查等操作。
二、实验内容JDBC实例开发。
使用SQL语句和JDBC来实现对数据库进行增删改查等操作。
把金老师发的实验内容整理好补充到这里三、实验要求1.熟练安装MyEclipse;2.熟练使用JDBC常用类;3.使用JDBC和SQL语句熟练进行数据库的查询和更新操作。
四、实验步骤1.安装MyEclipse;2.JDBC常用类、SQL语句对数据库进行查询和更新操作;3.编写测试驱动类,检查数据库连接和操作。
五、实验源代码及输出实验三Servlet和JSP实例开发一、实验目的熟悉Servlet和JSP技术,熟练使用Servlet和JSP开发动态交互式的应用,并与数据库技术结合,实现前台界面和后台数据库的交互开发。
二、实验内容使用Servlet和JSP开发动态交互式的应用,结合JDBC技术实现前台界面和后台数据库的交互开发。
任务一:实现对用户的增删改查三、实验要求1.熟练使用Servlet开发动态交互式网站;2.熟练使用JSP技术开发动态交互式网站;3.理解MVC架构;四、实验步骤1、创建任务所要求的数据库相关表,并添加相应的测试数据;2、开发Servlet代码实现任务一,对所实现功能进行测试;五、实验源代码及输出实验四Struts+Spring+Hibernate实例开发一、实验目的理解多层J2EE应用的设计思想,使用Struts、Spring和Hibernate三个框架构建多层J2EE 应用系统,熟悉表示层、业务逻辑层和数据访问层的设计原理,并利用框架技术开发一个简单的多层J2EE应用。
JSP仓库管理系统的设计与实现

JSP仓库管理系统的设计与实现一、引言随着电子商务的迅猛发展,仓库管理成为一个重要的环节。
传统的仓库管理主要依靠人工操作,效率低下且易出错。
为了提高仓库管理的效率和准确性,本文设计与实现了一套基于JSP技术的仓库管理系统。
二、需求分析1.仓库管理:用户可以进行仓库的增删改查操作,包括仓库信息的录入、修改和删除等。
2.库存管理:用户可以对仓库的库存进行管理,包括商品的入库和出库操作,以及库存的实时查询。
3.货物追踪:用户可以根据货物的编号查询货物的详细信息和相关操作记录。
4.用户管理:系统需要包含用户的登录和权限管理功能,管理员可以对用户进行增删改查操作。
三、系统设计1.数据库设计系统主要包括以下几个表:仓库信息表、货物信息表、入库记录表、出库记录表、用户表等。
其中,仓库和货物信息表是核心表,其他表与其有外键关联。
数据库采用MySQL进行设计和实现。
2.页面设计系统共包含以下页面:登录页面、主页、仓库管理页面、库存管理页面、货物追踪页面、用户管理页面等。
采用JSP技术进行页面的设计和开发,使用Bootstrap框架进行页面布局和样式美化。
3.功能实现(1)登录功能:用户输入用户名和密码进行登录,系统根据用户的权限跳转到相应的主页。
(2)仓库管理功能:用户可以对仓库信息进行增删改查操作,通过表格展示仓库信息,并提供表单进行录入和修改。
(3)库存管理功能:用户可以对库存进行操作,包括商品的入库和出库操作,以及查询库存信息。
用户输入商品编号和数量进行入库或出库操作,系统更新库存信息。
(4)货物追踪功能:用户可以根据货物编号查询货物的详细信息和相关操作记录,系统展示相关信息。
(5)用户管理功能:管理员可以对用户进行增删改查操作,包括用户的权限管理。
用户信息通过表格展示,并提供表单进行录入和修改。
四、系统实现1.环境准备系统开发环境为Windows,需安装Java开发环境、MySQL数据库、Tomcat服务器等。
SpringBoot实现简单的增删改查
SpringBoot实现简单的增删改查在pom.xml添加相应的依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 前端使⽤thymeleaf来代替jsp --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies>配置⽂件配置数据库等#serverserver.port=80#项⽬名:server.servlet.context-path#spring dataSourcespring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8ername=rootspring.datasource.password=rootmybatis.mapper-locations=classpath:/mapper/*/*.xml#spring log.cy=debug#spring thymeleaf(假如没有配置也会默认配置,在默认配置中prefix默认值为classpath:/templates/,后缀默认为.html)#不⽤重启服务器,⽹页就能刷新spring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/pages/spring.thymeleaf.suffix=.html数据层添加相应注解实现sql语句(或者通过xml配置来实现)数据层封装了商品信息,并提供get和set⽅法,为Goods类1.查询所有数据@Select("select * from tb_goods")List<Goods> findAll();2.按照id删除数据@Delete("delete from tb_goods where id=#{id}")int deleteById(Integer id);3.修改数据(1)修改数据⾸先要新建⼀个界⾯,按照id查找内容,并将查找到的内容显⽰到⽂本框内@Select("select * from tb_goods where id=#{id}")Goods findById(Integer id);(2)再添加查找的⽅法@Update("update tb_goods set name=#{name},remark=# {remark},createdTime=now() where id=#{id}")int update(Goods goods);4.新增数据@Insert("insert into tb_goods(name,remark,createdTime) values (#{name},#{remark},now())")int add(Goods goods);业务层提供对应接⼝⽅法和实现类1.业务层接⼝public interface GoodsService {List<Goods> findObject();int add(Goods goods);int update(Goods goods);Goods findById(Integer id);}2.业务层实现类@Servicepublic class GoodsServiceImpl implements GoodsService {@Autowiredprivate GoodsDao goodsDao;@Overridepublic List<Goods> findObject() {long start=System.currentTimeMillis();List<Goods> list = goodsDao.findObjects();long end=System.currentTimeMillis();System.out.println("query time:"+(end-start));return list;}@Overridepublic int add(Goods goods) {return goodsDao.add(goods);}@Overridepublic int update(Goods goods) {return goodsDao.update(goods);}@Overridepublic Goods findById(Integer id) {return goodsDao.findById(id);}控制层写具体实现1.跳转到⾸页并且查找所有商品@RequestMapping("doGoodsUI")public String doGoodsUI(Model model) {List<Goods> list = goodsService.findObject();model.addAttribute("goods",list);return "goods";}2.业务层实现类@Servicepublic class GoodsServiceImpl implements GoodsService {@Autowiredprivate GoodsDao goodsDao;@Overridepublic List<Goods> findObject() {long start=System.currentTimeMillis();List<Goods> list = goodsDao.findObjects();long end=System.currentTimeMillis();System.out.println("query time:"+(end-start));return list;}@Overridepublic int add(Goods goods) {return goodsDao.add(goods);}@Overridepublic int update(Goods goods) {return goodsDao.update(goods);}@Overridepublic Goods findById(Integer id) {return goodsDao.findById(id);}控制层写具体实现1.跳转到⾸页并且查找所有商品@RequestMapping("doGoodsUI")public String doGoodsUI(Model model) {List<Goods> list = goodsService.findObject();model.addAttribute("goods",list);return "goods";}2.删除商品@RequestMapping("doDeleteById/{id}")// (@PathVariable Integer id)告诉服务器,id拿到的是从⽹页上同样叫id的数据 public String dodeletebyId(@PathVariable Integer id){int delete = goodsDao.deleteById(id);//doGoodsUI前⾯没有加/的话,跳转的⽹址是替代了最后⼀个/后⾯的内容 return "redirect:/goods/doGoodsUI";}3.修改商品(1)先将查找出来的商品显⽰在⽂本框中@RequestMapping("doFindById/{id}")public String doFindByID(@PathVariable Integer id,Model model){Goods goods = goodsService.findById(id);model.addAttribute("goods",goods);return "goods-update";}(2)实现修改@RequestMapping("doUpdateGoods")public String doUpdateGoods(Goods goods){goodsService.update(goods);return "redirect:/goods/doGoodsUI";}4.新增商品@RequestMapping("doSaveGoods")public String doSaveGoods(Goods goods){goodsService.add(goods);return "redirect:/goods/doGoodsUI";}前端采⽤html+thymeleaf模板代替jsp2.each表⽰遍历拿到的数组,goods是从控制层拿到的model的名字3.id,name和remark与数据库对应,date要格式化拿到数据,该语法是thymeleaf固定写法<tr th:each="g:${goods}"><td th:text="${g.id}">1</td><td th:text="${}">AAAAAAA</td><td th:text="${g.remark}">aa</td><td th:text="${#dates.format(g.createdTime,'yyyy-MM-dd HH:mm')}">aa</td><!-- <td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doDeleteById(id=${g.id})}" rel="external nofollow" ><button>删除</button></a></td>--><td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doDeleteById/{doDeleteById}(doDeleteById=${g.id})}" rel="external nofollow" ><button>删除</button></a></td> <td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doFindById/{id}(id=${g.id})}" rel="external nofollow" ><button>修改</button></a></td></tr>4.新增商品界⾯(1)标签⾥的name属性要和sql语句⼀致(2)这⾥由于数据库中的id列设置了⾃增长,所以不需要id属性,createdTime列使⽤了now()获取当前时间,所以也不需要传值,所以在控制层的doUpdateGoods⽅法⾥可以使⽤封装好的Goods来接收从html拿到的参数<form th:action="@{/goods/doSaveGoods}" method="post"><ul><li>name:<input type="text" name="name"></li><li>remark:<textarea rows="3" cols="20" name="remark"></textarea></li><li><input type="submit" value="Save Goods"></li></ul></form>5.修改商品界⾯(1)因为id列⾃增长,所以修改商品信息不需要id这⼀列,但传参数有需要⼀起传送过去,所以添加了⼀个输⼊框,默认设置为隐藏,将其value设置为id的值<form th:action="@{/goods/doUpdateGoods}" method="post"><input type="hidden" name="id" th:value="${goods.id}"><ul><li>name:<input type="text" name="name" th:value="${}"></li><li>remark:<textarea rows="3" cols="20" name="remark" th:text="${goods.remark}"></textarea></li><li><input type="submit" value="Update Goods"></li></ul></form>以上就是Spring Boot实现简单的增删改查的详细内容,更多关于Spring Boot增删改查的资料请关注其它相关⽂章!。
jdbc操作oracle数据库(增删改查)
10.//生成getter、setter方法
11.publicvoidsetId<String id>
12.{
13.this.id = id ;
14.}
15.publicvoidsetName<String name>
16.{
= name ;
84.pstmt.setString<1,id> ;
85.//进行数据库更新操作
86.pstmt.executeUpdate<> ;
87.pstmt.close<> ;
88.}
89.catch<Exception e>
90.{
91.thrownewException<"操作出现异常"> ;
92.}
93.finally
2.importjava.sql.* ;
3.importjava.util.* ;
4.importcn.mldn.lxh.vo.* ;
5.importcn.mldn.lxh.dbc.* ;
6.importcn.mldn.lxh.dao.* ;
7.//此类需要完成具体的数据库操作,需要JDB代码
8.publicclassPersonDAOImplimplementsPersonDAO
76.PreparedStatement pstmt =null;
77.DataBaseConnection dbc =null;
78.//下面是针对数据库的具体操作
79.try
80.{
81.//连接数据库
82.dbc =newDataBaseConnection<> ;
jdbc数据库增、删、改、查语句
jdbc数据库增、删、改、查语句一、增加数据1. 插入单行数据在JDBC中,我们可以使用INSERT INTO语句来向数据库中插入单行数据。
例如,我们要向student表中插入一条新的学生记录,可以使用以下语句:INSERT INTO student (id, name, age) VALUES (1, '张三', 18);2. 批量插入数据如果我们要向数据库中插入多行数据,可以使用批量插入的方式,以提高效率。
例如,我们要向student表中插入多条新的学生记录,可以使用以下语句:INSERT INTO student (id, name, age) VALUES (1, '张三', 18), (2, '李四', 20), (3, '王五', 22);二、删除数据1. 删除指定行数据在JDBC中,我们可以使用DELETE FROM语句来删除数据库中的指定行数据。
例如,我们要删除student表中id为1的学生记录,可以使用以下语句:DELETE FROM student WHERE id = 1;2. 删除所有数据如果我们要删除数据库中的所有数据,可以使用DELETE FROM语句,并不指定任何条件。
例如,我们要删除student表中的所有学生记录,可以使用以下语句:DELETE FROM student;三、修改数据1. 更新指定行数据在JDBC中,我们可以使用UPDATE语句来更新数据库中的指定行数据。
例如,我们要将student表中id为1的学生记录的年龄修改为20岁,可以使用以下语句:UPDATE student SET age = 20 WHERE id = 1;2. 批量更新数据如果我们要更新数据库中的多行数据,可以使用批量更新的方式,以提高效率。
例如,我们要将student表中id为1和2的学生记录的年龄都修改为20岁,可以使用以下语句:UPDATE student SET age = 20 WHERE id IN (1, 2);四、查询数据1. 查询所有数据在JDBC中,我们可以使用SELECT语句来查询数据库中的数据。
java项目中的增删改查方法
java项目中的增删改查方法在Java项目中,增删改查(CRUD)操作是非常常见的需求。
无论是开发Web应用、移动应用还是后台系统,都会涉及到对数据的增加、删除、修改和查询操作。
在Java中,我们通常使用数据库来存储数据,而针对数据库的增删改查操作,我们通常会使用SQL语句来实现。
下面我们来看看在Java项目中,如何实现增删改查方法。
1. 增加(Create),在Java项目中,要实现数据的增加操作,通常需要先连接数据库,然后使用SQL语句向数据库中插入新的数据。
在Java中,我们可以使用JDBC(Java Database Connectivity)来连接数据库,使用PreparedStatement或者Statement来执行插入操作。
另外,如果我们使用了ORM框架(如Hibernate或MyBatis),我们也可以通过框架提供的API来实现数据的插入操作。
2. 删除(Delete),删除数据操作通常是根据某个条件从数据库中删除符合条件的数据。
在Java项目中,我们可以使用SQL的DELETE语句来实现数据的删除操作。
同样地,我们可以使用JDBC或者ORM框架提供的API来执行删除操作。
3. 修改(Update),修改数据操作通常是根据某个条件更新数据库中的数据。
在Java项目中,我们可以使用SQL的UPDATE语句来实现数据的更新操作。
同样地,我们可以使用JDBC或者ORM框架提供的API来执行更新操作。
4. 查询(Retrieve),查询数据操作是从数据库中检索数据。
在Java项目中,我们可以使用SQL的SELECT语句来实现数据的查询操作。
同样地,我们可以使用JDBC或者ORM框架提供的API来执行查询操作,并将查询结果返回给Java应用程序。
总的来说,在Java项目中实现增删改查方法,我们通常会使用JDBC来连接数据库并执行SQL语句,或者使用ORM框架来简化数据库操作。
无论是使用JDBC还是ORM框架,都需要对数据库操作有一定的了解,以便能够编写出高效、安全的增删改查方法。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
3,新建的normal工程
4,在src目录下建一个包,右击src选择new在选择package
5,输入合法名字比如bean
6,在bean目录下建一个class,右击bean选择new再选择class
7,输入名字Page
完整的Page.java代码如下
ﻩ }
ﻩ else{
currentPage=currentRecord/pageSize+1;
}
}
//获得和设置当前记录
public int getCurrentRecord(){
ﻩreturn currentRecord;
}
public voidsetCurrentRecord(intcurrentRecord){
先建个表student,
Createtable student (
id number(30)not nullprimarykey,
name varchar(50) ,
agenumber(30),
gendervarchar(30),
majorvarchar(50));
1,打开myeclipse(我用的是myeclipse8.5)新建一个webproject
ﻩﻩreturn gender;
ﻩ}
ﻩﻩpublicvoid setGender(Stringgender){
ﻩthis.gender=gender;
}
ﻩpublicString getMajor(){
ﻩﻩreturnmajor;
ﻩﻩ}
ﻩpublic voidsetMajor(String major){
packagebean;
publicclass Page{
privateint totalPage;
privateintcurrentPage;
privateint totalRecord;
private intcurrentRecord;
privateintpageSize=8;
//获得和设置当前页
this.currentRecord=currentRecord;
}
//获得和设置每页记录数量
public intgetPageSize(){
returnpageSize;
}
publicvoidsetPageSize(int pageSize){
this.pageSize=pageSize;
}
//获得和设置总页数
importjava.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
使用JSP+SERVLET+JDBC实现对数据库的增删改查
———————————————————————————————— 作者:
———————————————————————————————— 日期:
使用JSP+SERVLET+JDBC实现对数据库的增删改查
首先,打开sql*plus,输入用户名(我用的scott)密码(我设置的是tiger)。
ﻩthis.major=major;
ﻩ}
}
9,在src目录下添加另一个包dbservlet在该包中建立一个AllServlet类
完整的AllServlet.java代码如下
package dbservlet;
importjava.io.IOException;
import java.sql.Connection;
}
}
8,用相同的方法建一个StudentInfo类
完整的StudentInfo.java代码如下
packagebean;
public classStudentInfo{
ﻩprivate intid;ﻩﻩ //学号
private String name;//姓名
ﻩﻩprivateintage;//年龄
ﻩreturnname;
ﻩ}
ﻩpublicvoidsetName(String name){
ﻩthis.name=name;
ﻩ}
ﻩ
ﻩpublic int getAge(){
ﻩreturn age;
}
ﻩpublic void setAge(intage){
ﻩthis.age=age;
ﻩﻩ}
ﻩ
ﻩpublic StringgetGender(){
public intgetTotalPage(){
ﻩreturntotalPage;
}
public voidsetTotalPage(int totalRecord,intpageSize){
if(totalRecord%pageSize==0){
totalPage=totalRecord/pageSize;
ﻩﻩﻩthis.name=name;
ﻩthis.age=age;
ﻩﻩﻩthis.gender=gender;
ﻩthis.major=major;
ﻩ}
ﻩpublicint getId(){
ﻩﻩreturn id;
}
public voidsetId(intid){
ﻩﻩthis.id=id;
ﻩ}
ﻩpublicString getName(){
publicintgetCurrentPage(){
returncurrentPage;
}
publicvoidsetCurrentPage(int currentRecord,int pageSize){
ﻩif(currentRecord%pageSize==0){
ﻩ currentPage=currentRecord/pageSize;
ﻩﻩprivateString gender;//性别
privateString major;//专业
ﻩpublic StudentInfo(){
ﻩﻩ
}
ﻩﻩpublicStudentInfo(int id,String name,intage,Stringgender,Stringmajor){
ﻩﻩthis.id=d;
}
ﻩ else{
ﻩtotalPage=totalRecord/pageSize+1;
}
}
//获得和设置总记录
publicintgetTotalRecord(){
ﻩ returntotalRecord;
}
publicvoidsetTotalRecord(int totalRecord){
this.totalRecord=totalRecord;