pom.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>cn.abc</groupId>
<artifactId>maven_mysql</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
ItemsDao
import domain.Items;
import java.sql.SQLException;
import java.util.List;
public interface ItemsDao {
public List<Items> findAll() throws Exception;
}
ItemsDaoImpl
import dao.ItemsDao;
import domain.Items;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ItemsDaoImpl implements ItemsDao {
public List<Items> findAll() throws Exception {
List<Items> list = new ArrayList<Items>();
Connection connection = null;
PreparedStatement pst = null;
ResultSet resultSet = null;
try {
//加載驅動類
Class.forName("com.mysql.jdbc.Driver");
//獲取connection對象
connection = DriverManager.getConnection("jdbc:mysql:///users?useUnicode=true&characterEncoding=utf8","root","123456");
//獲取真正操作數據庫的對象
pst = connection.prepareCall("select * from user");
//執行數據庫查詢操作
resultSet = pst.executeQuery();
//把數據庫結果集轉爲list集合
while (resultSet.next()){
Items it = new Items();
it.setId(resultSet.getInt("id"));
it.setUsername(resultSet.getString("username"));
it.setPassword(resultSet.getString("password"));
list.add(it);
}
}catch (Exception e){
e.printStackTrace();
}finally {
connection.close();
pst.close();
resultSet.close();
}
return list;
}
}
Domain
public class Items {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
ItemsTest
import dao.ItemsDao;
import dao.impl.ItemsDaoImpl;
import domain.Items;
import org.junit.Test;
import java.util.List;
public class ItemsTest {
@Test
public void findAll() throws Exception {
ItemsDao dao = new ItemsDaoImpl();
List<Items> list = dao.findAll();
for (Items items : list) {
System.out.println(items.getId());
System.out.println(items.getUsername());
System.out.println(items.getPassword());
}
};
}