简单的目录
配置资源包
创建empBean(JavaBean)成员变量要和所查询的表保持一致
一定要切记上面的emp表的表项和empBean成员属性要保持一致
下面为empBean代码演示
public class empBean {
private Integer id;
private String name;
private String city;
private String country;
public empBean() {
}
public empBean(Integer id, String name, String city, String country) {
this.id = id;
this.name = name;
this.city = city;
this.country = country;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getcountry() {
return country;
}
public void setcountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "empBean{" +
"id=" + id +
", name='" + name + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}'+'\n';
}
}
接下来封装查询表以及代码
import com.alibaba.druid.pool.DruidDataSourceFactory;
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.Properties;
public class TestDbData {
public void selectAll() throws Exception{//查询表
Properties properties = new Properties();//java提供 读取配置资源包的对象
properties.load(new FileInputStream("src\\main\\java\\druid.properties"));//获取资源包
//获取德鲁伊参数数据,在我们的配置的资源包当中已经配置过了
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();//通过德鲁伊对象获取数据库连接
String sql = "select * from emp";//我们所要查询的sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);//预处理
ResultSet resultSet = preparedStatement.executeQuery();//获取处理sql语句或的resultSet
/**
* 先把查询结果放入empBean对象当中
* 创建一个集合用来存储empBean对象,是为了方便于以后将数据展示到客户端
*/
ArrayList<empBean> empBeans = new ArrayList<>();
//具体查询步骤如下
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String city = resultSet.getString("city");
String country = resultSet.getString("country");
empBean empBean = new empBean();
empBean.setId(id);
empBean.setName(name);
empBean.setCity(city);
empBean.setcountry(country);
empBeans.add(empBean);
}
for (empBean empBean : empBeans) {
System.out.println(empBean);
}
//关闭资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}
测试查询结果
public class DruidDemo {
public static void main(String[] args) throws Exception {
TestDbData testDbData = new TestDbData();
testDbData.selectAll();
}
}
结果对比上面的sql表和下面的结果
maven里面的配置信息
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> </dependency>