封装Druid连接池
public class LsDataSourceUtils {
public class LsDataSourceUtils { // 获取Druid数据库连接池对象 private static DataSource dataSource; /** * 使用静态代码块 读取配置文件内容 加载 Druid数据库连接池 */ static { try { // 读取src目录下 druid.properties Properties properties=new Properties(); InputStream resourceAsStream = LsDataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"); properties.load(resourceAsStream); // 交给我们的Druid数据库连接池 dataSource = DruidDataSourceFactory.createDataSource(properties); }catch (Exception e){ e.printStackTrace(); } } /** * 封装获取连接的方法 */ public static Connection getConnection(){ try { return dataSource.getConnection(); }catch (Exception e){ return null; } } /** * 释放jdbc连接 */ public static void close(Connection connection, Statement statement, ResultSet resultSet){ if(connection!=null){ try { connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(statement!=null){ try { statement.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } public static void close(Connection connection, Statement statement){ close(connection,statement,null); }
public class Test { public static void main(String[] args) throws SQLException { Connection connection=LsDataSourceUtils.getConnection(); // 获取预编译执行者对象 防止sql注入的问题 PreparedStatement preparedStatement= connection.prepareStatement("select *from user where id=? "); //设置参数 preparedStatement.setLong(1,2); //执行sql ResultSet resultSet=preparedStatement.executeQuery(); if(!resultSet.next()){ return; } // 对结果进行处理 // 获取该行数据第一列的id long id = resultSet.getLong("id"); // 获取该行数据第二列的name String name = resultSet.getString("name"); // 获取该行数据第三列的age int age = resultSet.getInt("age"); // 将db中查询到数据封装成user对象 UserEntity userEntity=new UserEntity(id,name,age); System.out.println(userEntity); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)