#代码目录
ItemsDaoIpul源码
package com.itheima.Dao.impl;
import com.itheima.Dao.ItemsDao;
import com.itheima.domin.Items;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class ItemsDaoImpl implements ItemsDao {
public List<Items> findAll() throws Exception{
List<Items> list=new ArrayList();
//先获取connection对象
Connection connection=null;
//获取真正操作数据的对象
PreparedStatement pst = null;
//执行数据库查询操作
ResultSet rs=null;
try{
//加载驱动类 Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql:///myemployees","root","");
//获取真正操作数据的对象
pst =connection.prepareCall("select * from employees");
//执行数据库查询操作
rs= pst.executeQuery();
//把数据库结果集转成java的List集合
while (rs.next()){
Items items=new Items();
items.setId(rs.getInt("employee_id"));
items.setName(rs.getString("first_name"));
list.add(items);
}
}catch(Exception e){
e.printStackTrace();
}finally {
connection.close();
pst.close();
rs.close();
}
return list;
}
}
xml配置文件源码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>maven_masql</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
</dependency>
</dependencies>
</project>
#Items源码
package com.itheima.domin;
public class Items {
private Integer id;
private String name;
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;
}
}
ItemsDao源码
package com.itheima.Dao;
import com.itheima.domin.Items;
import java.util.List;
public interface ItemsDao{
public List<Items> findAll() throws Exception;
}
#测试源码
package com.itheima.test;
import org.junit.Test;
import com.itheima.Dao.ItemsDao;
import com.itheima.Dao.impl.ItemsDaoImpl;
import com.itheima.domin.Items;
import java.util.List;
public class ItemsTest {
@Test
public void findAll() throws Exception{
ItemsDao itemsDao=new ItemsDaoImpl();
List<Items> list=itemsDao.findAll();
for (Items items :list){
System.out.println(items.getName());
}
}
}