JDBC数据库访问与JavaBean
Posted weixin_47940048
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC数据库访问与JavaBean相关的知识,希望对你有一定的参考价值。
一、增加新学号功能实现
用户点击“添加新学号”链接,页面跳转到addNum.jsp页面,在该页面中输入学号和名字信息,点击确认按钮,跳转到doAddNum.jsp页面;
doAddNum.jsp页面获取所输入的学号信息,使用JDBC将信息添加到数据表java2022;
添加完成跳转到showAllStudents.jsp页面。
//showAllStudents.jsp
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示所有学生信息</title>
</head>
<body>
<a href="addNum.jsp">添加学号</a>
<%
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2.建立与数据库的连接
String url = "jdbc:mysql://localhost:3306/java2022";
Connection conn = DriverManager.getConnection(url, "root", "root");
//3.创建命令对象
Statement st=conn.createStatement();
//4.执行SQL语句
String sql = "SELECT * FROM java2022";
ResultSet rs=st.executeQuery(sql);
//5.获取并输出查询结果
out.println("<table border='1'>");
out.println("<tr><td>学号num</td><td>姓名name</td>><td>编辑</td></tr>");
while (rs.next())
out.println("<tr>");
out.println("<td>"+rs.getString("num")+"</td>");
out.println("<td>"+rs.getString("name")+"</td>");
out.println("<td>");
out.println("<a href='updateNum.jsp?num="+rs.getString("num")+"'>修改</a>");
out.println("<a href='deleteNum.jsp?num="+rs.getString("num")+"'>删除</a>");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
//6.释放资源
rs.close(); st.close(); conn.close();
%>
</body>
</html>
//addNum.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加新学号</title>
</head>
<body>
<form action="doAddNum.jsp">
学号:<input type="text" name="num">
姓名:<input type="text" name="name">
<input type="submit" value="提交">
</form>
</body>
</html>
//doAddNum.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String num = request.getParameter("num");
String name = request.getParameter("name");
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javaee";
Connection conn = DriverManager.getConnection(url, "root", "123456");
String sql = "insert into java2022(num,name) values(?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, num);
pst.setString(2, name);
pst.executeUpdate();
response.sendRedirect("showAllStudents.jsp");
ps.close();
conn.close();
%>
</body>
</html>
二、根据学号num修改学生名字name实现
1.用户点击“编辑”链接,跳转到updateName.jsp文件,在该页面中显示并可修改指定num的名字信息,点击提交按钮,跳转到doUpdateName.jsp文件;
2.doUpdateName.jsp文件获取updateName.jsp文件中所输入的名字,根据学号修改学生名字;
3.修改完成跳转到showAllStudents.jsp页面。
//updateName.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改</title>
</head>
<body>
<%
String num = request.getParameter("num");
%>
<form action="doUpdateName.jsp">
学号:<input type="text" name="num" value="<%=num%>" readonly>
姓名:<input type="text" name="name">
<input type="submit" value="修改">
</form>
</body>
</html>
//doUpdateName.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String num = request.getParameter("num");
String name = request.getParameter("name");
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javaee";
Connection conn = DriverManager.getConnection(url, "root", "123456");
String sql = "update java2022 set name=? where num=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, num);
ps.executeUpdate();
response.sendRedirect("showAllStudents.jsp");
ps.close();
conn.close();
%>
</body>
</html>
三、根据学号num删除学生信息功能实现
1.用户点击“删除”链接,页面跳转到deleteNum.jsp文件,在该页面中获取学号num,根据学号num删除学生信息;
2.删除完成跳转到showAllStudents.jsp页面。
//deleteNum.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>删除学生信息</title>
</head>
<body>
<%
String num = request.getParameter("num");
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javaee";
Connection conn = DriverManager.getConnection(url, "root", "123456");
String sql = "delete from java2022 where num=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, num);
pst.executeUpdate();
response.sendRedirect("showAllStudents.jsp");
ps.close();
conn.close();
%>
</body>
</html>
四、JavaBean的创建,能够使用“代码法”和“标签法”两种方式建立JavaBean实例对象、设置属性和获取属性:
1) 在src下的pojo包中创建JavaBean,文件名为Student.java,具体内容如下:
成员变量:
num //学号,String类型,私有权限
name //姓名,String类型,私有权限
成员方法:
每一个属性对应的getter和setter方法,均为公有权限
2) 新建立一个javabean.jsp页面,用“代码法”和“标签法”创建JavaBean实例,设置、获取属性。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:useBean id="stu1" class="com.example.lab03.beans.Student">
<jsp:setProperty name="stu1" property="num" value="0123"/>
<jsp:setProperty name="stu1" property="name" value="张三"/>
<jsp:getProperty name="stu1" property="num"/>
<jsp:getProperty name="stu1" property="name"/>
</jsp:useBean>
<%
Student stu2 = new Student();
stu2.setNum("0456");
stu2.setName("李四");
out.print("<br>" + stu2.getNum() + stu2.getName());
%>
</body>
</html>
myBatis 基于javaBean配置
MyBatis的持久化解决方案是将用户从原始的JDBC访问中解放出来,用户只需要定义需要操作的SQL语句,
无须关注底层的JDBC操作,就可以以面向对象的方式来进行持久化层操作.底层数据库连接的获取,数据访问的实现,事务控制等都无须用户关心,
从而将应用层从底层的JDBC/JTA API抽取出来.通过配置文件管理JDBC连接,让MyBatis解决持久化的实现.在MyBatis中的常见对象有SqlSessionFactory和SqlSession.
依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>5.1.27</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
use类
public class User private Long id; private String username; private String address; @Override public String toString() return "User" + "id=" + id + ", username=‘" + username + ‘\\‘‘ + ", address=‘" + address + ‘\\‘‘ + ‘‘; public Long getId() return id; public void setId(Long id) this.id = id; public String getUsername() return username; public void setUsername(String username) this.username = username; public String getAddress() return address; public void setAddress(String address) this.address = address;
DataSourceConfig 数据源配置类
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig @Bean @ConfigurationProperties(prefix = "spring.datasource.one") DataSource dsOne() return DruidDataSourceBuilder.create().build(); @Bean @ConfigurationProperties(prefix = "spring.datasource.two") DataSource dsTwo() return DruidDataSourceBuilder.create().build();
MyBatisConfigOne
import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "org.javaboy.mybatis.mapper1", sqlSessionFactoryRef = "sqlSessionFactory1", sqlSessionTemplateRef = "sqlSessionTemplate1") public class MyBatisConfigOne @Autowired @Qualifier("dsOne") DataSource dsOne; @Bean SqlSessionFactory sqlSessionFactory1() SqlSessionFactory sessionFactory = null; try SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dsOne); sessionFactory = bean.getObject(); catch (Exception e) e.printStackTrace(); return sessionFactory; @Bean SqlSessionTemplate sqlSessionTemplate1() return new SqlSessionTemplate(sqlSessionFactory1());
MyBatisConfigTwo
import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "org.javaboy.mybatis.mapper2", sqlSessionFactoryRef = "sqlSessionFactory2", sqlSessionTemplateRef = "sqlSessionTemplate2") public class MyBatisConfigTwo @Autowired @Qualifier("dsTwo") DataSource dsOne; @Bean SqlSessionFactory sqlSessionFactory2() SqlSessionFactory sessionFactory = null; try SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dsOne); sessionFactory = bean.getObject(); catch (Exception e) e.printStackTrace(); return sessionFactory; @Bean SqlSessionTemplate sqlSessionTemplate2() return new SqlSessionTemplate(sqlSessionFactory2());
UserMapper1
import org.javaboy.mybatis.bean.User; import java.util.List; //@Mapper public interface UserMapper1 // @Select("select * from t_user") List<User> getAllUser();
UserMapper1.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.javaboy.mybatis.mapper1.UserMapper1"> <select id="getAllUser" resultType="org.javaboy.mybatis.bean.User"> select * from t_user; </select> </mapper>
UserMapper2
import org.javaboy.mybatis.bean.User; import java.util.List; //@Mapper public interface UserMapper2 // @Select("select * from t_user") List<User> getAllUser();
UserMapper2.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.javaboy.mybatis.mapper2.UserMapper2"> <select id="getAllUser" resultType="org.javaboy.mybatis.bean.User"> select * from t_user; </select> </mapper>
application.properties 配置文件
spring.datasource.one.url=jdbc:mysql:///test01 spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.one.driver-class-name=com.mysql.jdbc.Driver spring.datasource.two.url=jdbc:mysql:///test02 spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.two.driver-class-name=com.mysql.jdbc.Driver
以上是关于JDBC数据库访问与JavaBean的主要内容,如果未能解决你的问题,请参考以下文章