1.获取connection对象
先导入需要的jar包:mysql-connector-java;druid-jar
Properties pop = new Properties();
pop.load(new FileInputStream("src/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(pop);
Connection connection = dataSource.getConnection();
2.定义SQL语句
String sql = "select * from tb_brand";
3.获取PreparedStatement对象
PreparedStatement pstas = connection.prepareStatement(sql);
4.设置参数
5.执行sql
ResultSet rs = pstas.executeQuery();
6.处理结果
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");
String description = rs.getString("description");
int status = rs.getInt("status");
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);
7.释放资源
rs.close(); connection.close(); pstas.close();
2244

被折叠的 条评论
为什么被折叠?



