第二章 简单的JavaWeb项目

先导两个工具类

package utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * jdbc工具类
 *  1.单例模式 :一个类只有一个实例
 *  2.获取连接 : OK
 *  3.关闭资源
 *  4.开闭原则
 */
public class DBUtils {
    private static DBUtils dbUtils;
    private String driver;
    private String url;
    private String username;
    private String password;
    private DBUtils(){
        // 加载 配置 文件信息
        Properties pro = new Properties();
        try {
            pro.load(getClass().getClassLoader().getResourceAsStream("db.properties"));
            // 获取配置参数
            driver = pro.getProperty("jdbc.driverClassName");
            url = pro.getProperty("jdbc.url");
            username = pro.getProperty("jdbc.username");
            password = pro.getProperty("jdbc.password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static DBUtils getInstance() {
        if (dbUtils == null) {
            dbUtils = new DBUtils();
        }
        return dbUtils;
    }
    /**
     * 获取连接
     * @return 连接
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        Connection conn  = DriverManager.getConnection(url, username, password);
        return conn;
    }
    /**
     * 关闭连接
     * @param conn
     */

    public void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if(conn != null && ps != null && rs != null){
            try {
                conn.close();
                ps.close();
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容