5.18总结

package com.mf.jdbc.exmaple;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mf.jdbc.Brand;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**

  • 品牌数据的增删改查
    */

public class BrandTest {

/**
 * 查询所有
 * 1.SQL:select * from tb_brand
 * 2.参数:不需要
 * 3.结果:返回List<Brand>
 */

@Test
public void testSelectALL() throws Exception{
    //1.获取Connection
    Properties prop = new Properties();
    prop.load(new FileInputStream("./src/druid.properties"));
    //4.获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

    //5.获取数据库连接
    Connection conn = dataSource.getConnection();

    //定义sql
    String sql = "select * from tb_brand;";

    //获取pstmt对象
    PreparedStatement pstmt = conn.prepareStatement(sql);

    //设置参数

    //执行sql
    ResultSet rs = pstmt.executeQuery();

    //处理结果List<Brand> 封装Brand对象,装在List集合
    Brand brand = null;
    List<Brand> brands = new ArrayList<>();
    while (rs.next()){
        //获取数据
        int id = rs.getInt("id");
        String brandName = rs.getString("brand_name");
        String companyName = rs.getString("company_name");
        int ordered = rs.getInt("ordered");
        int status = rs.getInt("status");
        String description = rs.getString("description");
        //封装
        brand = new Brand();
        brand.setId(id);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(ordered);
        brand.setDescription(description);
        brand.setStatus(status);
        //装载到集合中去
        brands.add(brand);
    }
    System.out.println(brands);
    //释放资源
    rs.close();
    conn.close();
    pstmt.close();

}

}

posted @   奉禾  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示
主题色彩