JDBC封装的工具类
Posted zhulina-917
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC封装的工具类相关的知识,希望对你有一定的参考价值。
1. JDBC封装的工具类
public class JDBCUtil { private static Properties p = new Properties(); private static ThreadLocal<Connection> tl = new ThreadLocal(); static { InputStream stream = JDBCUtil.class.getResourceAsStream("/jdbc.properties"); try{ p.load(stream); } catch (Exception e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static Connection getConnection() { Connection connection = (Connection)tl.get(); if (connection == null) { try { Class.forName(p.getProperty("driver")); connection = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password")); tl.set(connection); } catch (Exception e) { e.printStackTrace(); } } return connection; } public static void close(Connection conn, PreparedStatement pst, ResultSet rs) { if (conn != null) { try { conn.close(); tl.remove(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.JDBC的配置文件
driver=oracle.jdbc.OracleDriver url=jdbc:oracle:thin:@localhost:1521:xe username=hr password=root
以上是关于JDBC封装的工具类的主要内容,如果未能解决你的问题,请参考以下文章
Java 中封装JDBC连接到JDBCUtils工具类的详解