JDBC Connection Pool Example

 

/*
 * Copyright (c) 1998 by Gefion software.
 *
 * Permission to use, copy, and distribute this software for
 * NON-COMMERCIAL purposes and without fee is hereby granted
 * provided that this copyright notice appears in all copies.
 *
 */

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * This class is a Singleton that provides access to one or many
 * connection pools defined in a Property file. A client gets
 * access to the single instance through the static getInstance()
 * method and can then check-out and check-in connections from a pool.
 * When the client shuts down it should call the release() method
 * to close all open connections and do other clean up.
 */
public class DBConnectionManager {
    static private DBConnectionManager instance;       // The single instance
    static private int clients;

    private Vector drivers = new Vector();
    private PrintWriter log;
    private Hashtable pools = new Hashtable();
   
    /**
     * Returns the single instance, creating one if it's the
     * first time this method is called.
     *
     * @return DBConnectionManager The single instance.
     */
    static synchronized public DBConnectionManager getInstance() {
        if (instance == null) {
            instance = new DBConnectionManager();
        }
        clients++;
        return instance;
    }
   
    /**
     * A private constructor since this is a Singleton
     */
    private DBConnectionManager() {
        init();
    }
   
    /**
     * Returns a connection to the named pool.
     *
     * @param name The pool name as defined in the properties file
     * @param con The Connection
     */
    public void freeConnection(String name, Connection con) {
        DBConnectionPool pool = (DBConnectionPool) pools.get(name);
        if (pool != null) {
            pool.freeConnection(con);
        }
    }
       
    /**
     * Returns an open connection. If no one is available, and the max
     * number of connections has not been reached, a new connection is
     * created.
     *
     * @param name The pool name as defined in the properties file
     * @return Connection The connection or null
     */
    public java.sql.Connection getConnection(String name) {
        DBConnectionPool pool = (DBConnectionPool) pools.get(name);
        if (pool != null) {
            return pool.getConnection();
        }
        return null;
    }
   
    /**
     * Returns an open connection. If no one is available, and the max
     * number of connections has not been reached, a new connection is
     * created. If the max number has been reached, waits until one
     * is available or the specified time has elapsed.
     *
     * @param name The pool name as defined in the properties file
     * @param time The number of milliseconds to

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
学生管理系统是一个比较典型的CRUD应用,我们可以使用JSP + JDBC + MySQL来实现。 首先,我们需要创建一个数据库,包含学生信息的表。可以创建一个名为`student`的表,包含以下字段: ``` id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, age int(11) NOT NULL, gender varchar(10) NOT NULL, phone varchar(20) DEFAULT NULL, address varchar(100) DEFAULT NULL, PRIMARY KEY (id) ``` 接下来,我们需要创建一个JDBC连接池,以便在应用中共享数据库连接。可以使用Tomcat自带的连接池,或者使用第三方的连接池库。这里我们使用Tomcat自带的连接池。 在`context.xml`文件中添加以下内容: ``` <Context> <Resource name="jdbc/student" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="数据库用户名" password="数据库密码" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8"/> </Context> ``` 在`web.xml`文件中添加以下内容: ``` <resource-ref> <description>Connection pool for MySQL</description> <res-ref-name>jdbc/student</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> ``` 然后,我们可以编写一个JavaBean来代表学生对象。在`Student.java`文件中添加以下内容: ```java public class Student { private int id; private String name; private int age; private String gender; private String phone; private String address; // 省略getter和setter方法 } ``` 接下来,我们可以编写一个DAO类来访问数据库。在`StudentDAO.java`文件中添加以下内容: ```java public class StudentDAO { private DataSource dataSource; public StudentDAO() throws NamingException { Context context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/student"); } public List<Student> getAllStudents() throws SQLException { List<Student> students = new ArrayList<>(); try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student")) { while (rs.next()) { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); student.setGender(rs.getString("gender")); student.setPhone(rs.getString("phone")); student.setAddress(rs.getString("address")); students.add(student); } } return students; } public Student getStudentById(int id) throws SQLException { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM student WHERE id=?")) { stmt.setInt(1, id); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); student.setGender(rs.getString("gender")); student.setPhone(rs.getString("phone")); student.setAddress(rs.getString("address")); return student; } } } return null; } public void addStudent(Student student) throws SQLException { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO student (name, age, gender, phone, address) VALUES (?, ?, ?, ?, ?)")) { stmt.setString(1, student.getName()); stmt.setInt(2, student.getAge()); stmt.setString(3, student.getGender()); stmt.setString(4, student.getPhone()); stmt.setString(5, student.getAddress()); stmt.executeUpdate(); } } public void updateStudent(Student student) throws SQLException { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement( "UPDATE student SET name=?, age=?, gender=?, phone=?, address=? WHERE id=?")) { stmt.setString(1, student.getName()); stmt.setInt(2, student.getAge()); stmt.setString(3, student.getGender()); stmt.setString(4, student.getPhone()); stmt.setString(5, student.getAddress()); stmt.setInt(6, student.getId()); stmt.executeUpdate(); } } public void deleteStudent(int id) throws SQLException { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("DELETE FROM student WHERE id=?")) { stmt.setInt(1, id); stmt.executeUpdate(); } } } ``` 最后,我们可以编写一个JSP页面来展示学生信息。在`index.jsp`文件中添加以下内容: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.List" %> <%@ page import="javax.naming.NamingException" %> <%@ page import="com.example.StudentDAO" %> <%@ page import="com.example.Student" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生管理系统</title> </head> <body> <h1>学生列表</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>电话</th> <th>地址</th> <th></th> </tr> <% StudentDAO dao = null; try { dao = new StudentDAO(); List<Student> students = dao.getAllStudents(); for (Student student : students) { %> <tr> <td><%= student.getId() %></td> <td><%= student.getName() %></td> <td><%= student.getAge() %></td> <td><%= student.getGender() %></td> <td><%= student.getPhone() %></td> <td><%= student.getAddress() %></td> <td> <a href="edit.jsp?id=<%= student.getId() %>">编辑</a> <a href="delete.jsp?id=<%= student.getId() %>" onclick="return confirm('确定删除?')">删除</a> </td> </tr> <% } } catch (SQLException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } finally { if (dao != null) { dao.close(); } } %> </table> <p><a href="add.jsp">添加学生</a></p> </body> </html> ``` 在`edit.jsp`文件中,我们可以使用同样的方式显示学生信息,并提供一个表单来编辑学生信息。在提交表单时,我们可以使用`StudentDAO`类来更新学生信息。 在`add.jsp`文件中,我们可以提供一个表单来添加新的学生信息。在提交表单时,我们可以使用`StudentDAO`类来插入新的学生信息。 在`delete.jsp`文件中,我们可以使用`StudentDAO`类来删除学生信息。 至此,我们已经完成了一个简单的学生管理系统的实现。注意,在实际应用中,我们需要进行一些安全性和可靠性的考虑,例如输入验证、异常处理、事务管理等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

skyyoung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值