数据库连接池_druid工具类和数据库连接池_druid工具类测试
数据库连接池_druid工具类:
1.定义工具类
定义一个类JDBCUtils
提供静态代码块加载配置文件,初始化连接池对象
提供方法
1.获取连接方法:通过数据库连接池获取连接
2.释放资源
3.获取连接池的方法
代码实现:
/** * Druid连接池的工具类 */ public class JDBCUtils { // 1.定义成员变量 DataSource private static DataSource ds; static { try { // 1.配置文件 Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); // 2.获取DataSource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(ResultSet rs, Statement stmt, Connection conn) { // 归还连接 if (rs != null) { try { rs.close(); } catch (SQLException es) { es.printStackTrace(); } } // 归还连接 if (stmt != null) { try { stmt.close(); } catch (SQLException es) { es.printStackTrace(); } } // 归还连接 if (conn != null) { try { conn.close(); } catch (SQLException es) { es.printStackTrace(); } } } public static void close(Statement stmt, Connection conn) { // 归还连接 // if (stmt != null) { // try { // stmt.close(); // } catch (SQLException es) { // es.printStackTrace(); // } // } // // 归还连接 // if (conn !=null) { // try { // conn.close(); // } catch (SQLException es) { // es.printStackTrace(); // } // } close(null,stmt,conn); } /** * 获取数据库连接 * @return */ public static DataSource getDataSource() { return ds; } }
数据库连接池_druid工具类测试:
代码实现:
public class DruidDemo2 { public static void main(String[] args) { /* * 完成添加操作:给account表添加一条记录 */ Connection conn = null; PreparedStatement pst = null; try { // 1.获取连接 conn = JDBCUtils.getConnection(); // 2.定义sql String sql = "insert into account values(null,?,?)"; // 3.获取pst对象 pst = conn.prepareStatement(sql); // 4.给?赋值 pst.setString(1,"王五"); pst.setDouble(2,3000); // 5.执行sql int count = pst.executeUpdate(); System.out.println(count); } catch (SQLException es) { es.printStackTrace(); } finally { // 6.释放资源 JDBCUtils.close(pst,conn); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix