封装工具类
为了减少代码工作量,将JDBC注册、获取连接、释放连接封装为一个工具类;
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class JDBCUtils { private static DataSource ds; static{ try { Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(Statement stmt,Connection conn){ if(stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs, Statement stmt, Connection conn){ if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static DataSource getDataSource(){ return ds; } }
|
调用工具类
调用工具类具体实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class DruidDemo2 { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); String sql = "insert into account values(null,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1,"王五"); pstmt.setDouble(2,3000); int count = pstmt.executeUpdate(); System.out.println(count); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.close(pstmt,conn); } } }
|