封装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);

    }


}
复制代码

 

posted @   彷佛昨天  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示