• JDBCUtil


    package com.baizhi.JDBCUtil;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Properties;
    
    public class JDBCUtil {
        static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); 
        private static String className;
        private static String url;
        private static String user;
        private static String pwd;
        static Properties pro = null;
        static {
            //创建properties
            pro = new Properties();
            //获取输入流
            InputStream is = JDBCUtil.class.getResourceAsStream("/JDBCUtil.properties");
            //读取JDBCUtil.properties
            try {
                pro.load(is);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //获取键值对
             className = pro.getProperty("ClassName");
             url = pro.getProperty("url");
             user = pro.getProperty("user");
             pwd = pro.getProperty("psw");
        }
        //加载驱动.获取连接
        public static Connection getConn() {
            if (tl.get() == null) {
                try {
                    Class.forName(className);
                    Connection conn = DriverManager.getConnection(url, user,pwd);
                    tl.set(conn);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } 
            return tl.get();
        }
        
        
        //关闭资源    
        public static void closeAll(Connection conn,PreparedStatement pstm,ResultSet rs) {
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(pstm != null) {
                try {
                    pstm.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(conn != null) {
                try {
                    tl.remove();
                    conn.close();    
                } catch (SQLException e) {
                    throw new RuntimeException(e+"关闭conn链接出错");
                }
            }
        }
    }

    配置文件 (properties)

    ClassName = oracle.jdbc.OracleDriver
    url = jdbc:oracle:thin:@localhost:1521:xe
    user = hr
    psw = hr
    以粮为纲全面发展
  • 相关阅读:
    apscheduler 踩坑
    fastapi 导出excel文件
    python flask 使用日志
    git 头指针游离问题
    C# 连接mysql填坑
    前端项目proxy小问题
    需完善--日志框架
    依赖<dependency>的scope了解
    git 退回到指定tag版本
    git切换远程仓库地址
  • 原文地址:https://www.cnblogs.com/alexliuf/p/13515176.html
Copyright © 2020-2023  润新知