jdbc的增删改查

传智播客——jdbc的增删改查 收藏

今天我们做了一个例子就是利用jdbc的知识对数据库进行增删改查,今天我把佟老师讲的思路在计算机上打了一遍,这个例题是对标签,数据库,和类加载的一个小复习!代码和步骤如下!
(1)增加数据操作
要在servlet中实现以下几点
获取客户端浏览器的请求参数
封装请求信息到一个 JavaBean中
调用 CustomerDAO 方法
根据方法的执行情况确定派发页面
若不出现异常
出现异常
派发页面
第一部页面显示代码,
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>My JSP 'searchCustomer.jsp' starting page</title>
</head>

<body>
<c:if test="${requestScope.errorInfo != null}">
<font color="red">${requestScope.errorInfo}</font>
<br><br>
</c:if>
<form action="addnewcustomer" method="post">
<table>
<tr>
<td>^^Name:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add"/></td>
</tr>
</table>
</form>
</body>
</html>
第二部:进入select容器中

public class AddNewCustomer extends HttpServlet implements Servlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 解析客户端的请求参数
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");

//2. 把获取到的参数封装成一个 Customer 对象
Customer cust = new Customer(name, address, phone);

//3. 调用 CustomerDAO.saveCustomer(Customer customer) 方法
CustomerDAO customerDAO = new CustomerDAO();

//4. 决定要派发的页面: 若方法没有异常出现, 派发页面为 success.jsp; 若有异常, 派发页面为 addcustomer.jsp,
// 并给出错误提示信息
String forwardPage = null;
try {
customerDAO.saveCustomer(cust);
forwardPage = "success.jsp";
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorInfo", e.getMessage());
forwardPage = "addcustomer.jsp";
}

//5. 页面的派发
RequestDispatcher dispatcher = null;
dispatcher = request.getRequestDispatcher(forwardPage);
dispatcher.forward(request, response);
}
}
第三步调用 CustomerDAO.saveCustomer(Customer customer) 方法
把 customer 对象保存到数据库中
* @param customer
*/
public void saveCustomer(Customer customer){
Connection conn = null;
PreparedStatement ps = null;

try {
//1. 获取数据库连接
conn = DBManager.getConnection();

//2. 准备预编译的 sql 语句
String sql = "INSERT INTO customers(name, address, phone) VALUES(?, ?, ?)";

//3. 获取 PreparedStatement 对象
ps = conn.prepareStatement(sql);

//4. 填充 编译的 sql 语句中的参数
ps.setString(1, customer.getName());
ps.setString(2, customer.getAddress());
ps.setString(3, customer.getPhone());

//5. 发送 sql 语句
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();

String errorMsg = "Duplicate entry '" + customer.getName() + "' for key 2";
String errorMsg_ = "您选择的用户名 " + customer.getName() + " 已被占用, 请重新输入新的用户名";

if(errorMsg.equals(e.getMessage()))
throw new RuntimeException(errorMsg_, e);

throw new RuntimeException(e);

} finally{
//6. 释放数据库资源
DBManager.releaseDBSource(null, ps, conn);
}

}
}
第四部按以上步骤可以实现对数据的增加
还需要一个加载类

/**
* 数据库操作的工具类
* @author Administrator
*
*/
public final class DBManager {
/**
* 私有化构造器, 不允许创建工具类的对象
*/
private DBManager(){}

/**
* 连接数据库的基本信息
*/
private static String user;
private static String password;
private static String url;
private static String driver;

/**
* 对 user 等四个静态变量进行初始化
* 1. 创建一个 Properties 对象
* 2. 使用类加载器加载 mysql.properties 文件对应的输入流
* 3. 获取 mysql.properties 文件中的四个属性值
* 4. 对 user 等四个静态变量进行初始化
*/
static{
try {
Properties props = new Properties();
InputStream propsIs = DBManager.class.getClassLoader().getResourceAsStream("mysql.properties");
props.load(propsIs);
user = props.getProperty("user");
password = props.getProperty("password");
url = props.getProperty("url");
driver = props.getProperty("driver");
} catch (IOException e) {
e.printStackTrace();
}

}

/**
* 获取数据库连接
*/
public static Connection getConnection(){
Connection conn = null;

try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("连接数据库服务器失败, 请检查数据库服务器的状态", e);
}

return conn;
}

/**
* 关闭数据库资源
*/
public static void releaseDBSource(ResultSet rs, Statement st, Connection conn){
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
以下介绍删除操作在控制区中的代码依旧是servlet中的代码与步骤
删除:public class CustomerUIServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取需要修改的 customer 的 id
String idStr = request.getParameter("id");

//2. 调用 CustomerDAO.findCustomerById(int customerId) 获取对应的 Customer 对象;
CustomerDAO customerDAO = new CustomerDAO();


//3.1 若不出现异常, 且用户该存在, 则把 Customer 对象放置到 request 域中,
// 确定派发页面为: customerUI.jsp, 利用 EL 和 JSTL 在该页面显示该 Customer 的详细信息
String forwardPage = null;

try {
Customer cust = customerDAO.findCustomerById(Integer.parseInt(idStr));
request.setAttribute("customer", cust);
forwardPage = "customerUI.jsp";
}
//3.2 若出现异常, 则派发到 searchCustomers.jsp 页面, 要求该页面还继续显示之前的 Customer 信息,
// 给出对应的异常信息提示
catch (NumberFormatException e) {
e.printStackTrace();
request.setAttribute("errorInfo", "您输入的 id 格式不正确");
forwardPage = "searchcustomers";
} catch(Exception ex){
request.setAttribute("errorInfo", ex.getMessage());
forwardPage = "searchcustomers";
}

//4. 派发页面
RequestDispatcher dispatcher = null;
dispatcher = request.getRequestDispatcher(forwardPage);
dispatcher.forward(request, response);
}
}
查找:protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取客户端浏览器的请求参数
String name = null;
String address = null;
String phone = null;

name = request.getParameter("name");
address = request.getParameter("address");
phone = request.getParameter("phone");

//2. 封装请求信息到一个 Customer 对象中
Customer cust = new Customer(name, address, phone);

//3. 调用 CustomerDAO 的 searchCustomers(Customer) 方法
CustomerDAO customerDAO = new CustomerDAO();

//4. 根据方法的执行情况确定派发页面
String forwardPage = null;

try {
List custs = customerDAO.searchCustomers(cust);
//4.1 若不出现异常, 派发页面为 searchCustomers.jsp, 需要在该页面显示 customer 信息
request.setAttribute("customers", custs);
forwardPage = "searchCustomers.jsp";
} catch (Exception e) {
e.printStackTrace();
//4.2 出现异常, 派发页面为 searchCustomers.jsp, 给出错误提示
request.setAttribute("errorInfo", e.getMessage());
forwardPage = "searchCustomers.jsp";
}

//5. 派发页面
RequestDispatcher dispatcher = null;
dispatcher = request.getRequestDispatcher(forwardPage);
dispatcher.forward(request, response);
}
}
更新:String forwardPage = null;
try {
//2. 把请求参数封装成一个 Customer 对象
Customer cust = new Customer(name, address, phone);
cust.setId(Integer.parseInt(idStr));

request.setAttribute("customer", cust);

//3. 调用 CustomerDAO.updateCustomer(Cucstomer cust) 方法
CustomerDAO customerDAO = new CustomerDAO();
int result = customerDAO.updateCustomer(cust);

//4. 根据方法的执行情况确定派发页面
if(result == 1){
//4.1 若方法返回值为 1, 则派发页面为: searchCustomers.jsp, 使该页面显示修改成功之后的 customer 列表信息
forwardPage = "searchcustomers";
}else{
//4.2 若方法返回值为 0, 说明修改的用户信息不存在, 派发页面为: customerUI.jsp, 现实异常信息, 而且还要对已经填写好的信息进行回显
request.setAttribute("errorInfo", "要修改的用户不存在");
}
} catch (NumberFormatException e) {
e.printStackTrace();
//4.3 若出现异常, 者派发页面为: customerUI.jsp, 现实异常信息, 而且还要对已经填写好的信息进行回显
request.setAttribute("errorInfo", "您输入的 id 格式不正确");
forwardPage = "customerUI.jsp";
} catch(Exception ex){
request.setAttribute("errorInfo", ex.getMessage());
forwardPage = "customerUI.jsp";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDBC(Java Database Connectivity)是一种用于执行SQL语句的Java API,它提供了一种连接到数据库的标准方式。下面是JDBC增删改查的详细步骤: 1. 加载JDBC驱动程序 在使用JDBC之前,必须加载适合于数据库的JDBC驱动程序。不同的数据库有不同的JDBC驱动程序,因此你需要根据你使用数据库加载相应的驱动程序。例如: ``` Class.forName("com.mysql.jdbc.Driver"); ``` 2. 建立数据库连接 在加载完JDBC驱动程序之后,就可以建立与数据库之间的连接了。连接的过程需要提供数据库的URL、用户名和密码。例如: ``` String url = "jdbc:mysql://localhost:3306/test?useSSL=false"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); ``` 3. 创建Statement对象 在建立好数据库连接之后,就可以创建一个Statement对象。Statement对象用于执行SQL语句并返回结果。例如: ``` Statement statement = connection.createStatement(); ``` 4. 执行SQL语句 接下来,可以使用Statement对象执行SQL语句。例如: ``` String sql = "SELECT * FROM user"; ResultSet resultSet = statement.executeQuery(sql); ``` 如果要执行增、删、改操作,则可以使用Statement对象的executeUpdate()方法。例如: ``` String sql = "INSERT INTO user(name, age) VALUES('张三', 20)"; statement.executeUpdate(sql); ``` 5. 处理结果集 如果执行的是查询操作,则需要处理查询结果集。查询结果集以ResultSet对象的形式返回。例如: ``` while (resultSet.next()) { String name = resultSet.getString("name"); int age = resultSet.getInt("age"); System.out.println("name: " + name + ", age: " + age); } ``` 6. 关闭连接 在完成JDBC操作之后,需要关闭与数据库的连接。例如: ``` resultSet.close(); statement.close(); connection.close(); ``` 以上就是JDBC增删改查的详细步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值