1.首先准备数据库表tb_brand
2.创建实体类
src下创建java包 brand
ctrl+r可以快速替换相同字符
package pojo;
public class brand {
private Integer id;
private String brandName;
private String companyName;
private int ordered;
private String description;
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getOrdered() {
return ordered;
}
public void setOrdered(int ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
下载junit的jar包进行单元测试
jar包链接:
jar包
jar包
两个都要下载并且导入包内
BrandTest测试代码:
package pojo;
import com.alibaba.druid.pool.DruidDataSourceFactory;
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 {
@Test
public void testSelectAll() throws Exception{
// 1,获取conneiton
// 3.加载配置文件
Properties prop =new Properties();
prop.load(new FileInputStream("C:\\Users\\lengxin\\IdeaProjects\\jdbc-demo\\lib\\druid.properties"));
// 4.获取连接池数据对象
DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
// 5.获取数据库链接
Connection conn=dataSource.getConnection();
// 2.定义sql语句
String sql ="select * from tb_brand";
// 3.获取pstmt对象
PreparedStatement pstmt = conn.prepareStatement(sql);
// 4。设置参数
// 5.执行sql
ResultSet rs=pstmt.executeQuery();
// 6.处理结果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");
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();
pstmt.close();
conn.close();
}
}
运行代码
小结:
1.要思考写什么样的sql语句,实现什么样的功能
2.需不需要参数
3.功能完成后,需要返回什么样子的数据