JDBC连接数据库(Servlet+JSP)

时间:2023-12-12 12:38:32

  JDBC(Java Database connectivity),是连接数据库的一种方式。后面的框架Mybatis和Hibernate等都封装的是JDBC。在JDBC中常用的API有4个:DriverManager、Connection、Statement、ResultSet。

代码演示:

  首先要导入jar包: jstl_el、jstl-1.2_1、mysql-5.1.10

User.java

 public class User {
private int id;
private String age;
private String name; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

QueryServlet.java

 package cn.woo.servlet;

 import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import cn.woo.entity.User;
import cn.woo.util.DBUtil; /**
* 类说明:接收请求的Servlet
*
* @author wyh
* @version 创建时间:2018年8月23日 下午2:46:29
*/
public class QueryServlet extends HttpServlet { /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8"); String action = req.getParameter("action");
List<User> userList = new ArrayList<>(); switch (action) {
case "getUserList":
try {
ResultSet resultSet = DBUtil.query("select * from user");
// 遍历结果集【一行行数据读取】,将结果集放置到实体对象中
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setAge(String.valueOf(resultSet.getInt("age")));
user.setName(resultSet.getString("name"));
userList.add(user);
}
req.setAttribute("userList",userList);
// 跳转至展示页面
req.getRequestDispatcher("../UserList.jsp").forward(req, resp);
} catch (SQLException e) {
e.printStackTrace();
}finally {
// 释放资源
DBUtil.closeResource();
}
break;
case "deleteUserInfo":
try {
String id = req.getParameter("id");
int delResult = DBUtil.insertOrDeleteOrUpdate("delete from user where id='"+id+"'");
if(delResult>0) {
System.out.println("删除成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
break;
case "updateUserName":
try {
String id = req.getParameter("id");
String name = req.getParameter("name");
int updateResult = DBUtil.insertOrDeleteOrUpdate("update user set name='"+name+"' where id='"+id+"'");
if(updateResult>0) {
System.out.println("更新用户名成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
break;
case "insertUserInfo":
try {
String addAge = req.getParameter("age");
String addName = req.getParameter("name");
int addResult = DBUtil.insertOrDeleteOrUpdate("insert into user(age,name) value('"+addAge+"','"+addName+"')");
if(addResult>0) {
System.out.println("新增用户成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}

UserList.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户信息列表</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
} table{
margin: 300px auto;
} td{
width:100px;
text-align: center;
}
</style>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td>序号</td>
<td>工号</td>
<td>年龄</td>
<td>姓名</td>
</tr>
<c:forEach items="${ userList }" var="user" varStatus="status">
<tr>
<td>${ status.index+1 }</td>
<td>${ user.id }</td>
<td>${ user.age }</td>
<td>${ user.name }</td>
</tr>
</c:forEach>
</table>
</body>
</html>

DBUtil.java

 package cn.woo.util;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; /**
* 类说明:数据库连接工具类
* @author wyh
* @version 创建时间:2018年8月23日 下午3:58:55
*/
public class DBUtil { private static Connection connection;
private static Statement statement; static {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 获取连接 【并设置编码方式】
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/woo?unicode=true&characterEncoding=UTF-8","root","root");
} catch (SQLException e) {
e.printStackTrace();
}
} public static Statement getStatement() throws SQLException {
// 获取statement 【用于执行SQL语句】
statement = connection.createStatement();
return statement;
} /**
* 查
* @param sql 执行查询的sql语句
* @return resultSet 返回的结果集
* @throws SQLException
*/
public static ResultSet query(String sql) throws SQLException {
return getStatement().executeQuery(sql);
} /**
* 增/删/改 通用方法
* @param sql 要执行的SQL语句
* @return 执行结果 >0表明执行成功
* @throws SQLException
*/
public static int insertOrDeleteOrUpdate(String sql) throws SQLException {
return getStatement().executeUpdate(sql);
} /**
* 释放资源
*/
public static void closeResource() {
try {
if(statement!=null) {
statement.close();
}
if(connection!=null) {
connection.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}