文章目錄
- 七、實現步驟
- (六)創建數據訪問接口實現類
- 1、創建學校數據訪問接口實現類
- 單元測試:對CollegeDaoImpl進行單元測試
- 2、創建狀態數據訪問接口實現類
- 單元測試:對StatusDaoImpl進行單元測試
- 3、學生數據訪問接口實現類
- 單元測試:對StudentDaoImpl進行單元測試
- (1)編寫測試方法testInsert()
- (2)編寫測試方法testDeleteById()
- (3)編寫測試方法testDeleteByClass()
- (4)編寫測試方法testFindByName()
- (5)編寫測試方法testFindAll()
- (6)編寫測試方法testFindRowsBySex()
- 獨立完成剩餘方法的測試任務
- (1)編寫測試方法testDeleteByDepartment()
- (2)編寫測試方法testUpdate()
- (3)編寫測試方法testFindById()
- (4)編寫測試方法testFindByClass()
- (5)編寫測試方法testFindByDepartment()
- (6)編寫測試方法testFindRowsByClass()
- (7)編寫測試方法testFindRowsByDepartment()
- 4、創建用戶數據訪問接口實現類
- 單元測試:對UserDaoImpl進行單元測試
- 獨立完成剩餘方法的測試任務
七、實現步驟
(六)創建數據訪問接口實現類
- 在
net.hw.student.dao
包裏創建impl
子包,然後在裏面創建四個數據訪問接口的實現類。
1、創建學校數據訪問接口實現類
- 創建學校數據訪問接口實現類CollegeDaoImpl
package net.hw.student.dao.impl;
import net.hw.student.bean.College;
import net.hw.student.dao.CollegeDao;
import net.hw.student.dbutil.ConnectionManager;
import java.sql.*;
/**
* 功能:學校數據訪問接口實現類
* 作者:華衛
* 日期:2020年06月05日
*/
public class CollegeDaoImpl implements CollegeDao {
/**
* 按id查找學校
*
* @param id
* @return 學校對象
*/
@Override
public College findById(int id) {
// 定義學校對象
College college = null;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_college where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setInt(1, id);
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
// 實例化學校對象
college = new College();
// 利用當前記錄各個字段值去設置學校對象的屬性
college.setId(rs.getInt("id"));
college.setName(rs.getString("name"));
college.setPresident(rs.getString("president"));
college.setStartTime(rs.getTimestamp("start_time"));
college.setTelephone(rs.getString("telephone"));
college.setEmail(rs.getString("email"));
college.setAddress(rs.getString("address"));
college.setProfile(rs.getString("profile"));
}
// 7. 關閉預備語句對象
pstmt.close();
// 8. 關閉結果集對象
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學校對象
return college;
}
/**
* 更新學校信息
*
* @param college
* @return 更新記錄數
*/
@Override
public int update(College college) {
// 定義更新記錄數
int count = 0;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "update t_college set name = ?, president = ?, start_time = ?,"
+ " telephone = ?, email = ?, address = ?, profile = ? where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, college.getName());
pstmt.setString(2, college.getPresident());
pstmt.setTimestamp(3, new Timestamp(college.getStartTime().getTime()));
pstmt.setString(4, college.getTelephone());
pstmt.setString(5, college.getEmail());
pstmt.setString(6, college.getAddress());
pstmt.setString(7, college.getProfile());
pstmt.setInt(8, college.getId());
// 5. 執行SQL,返回更新記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回更新記錄數
return count;
}
}
單元測試:對CollegeDaoImpl進行單元測試
爲了確保Dao層給上層提供正確的數據操作服務,應該進行單元測試,本項目採用JUnit4單元測試框架。
- 在根包net.hw.student裏創建test子包,在裏面創建測試類TestCollegeDaoImpl
(1)編寫測試方法testFindById()
- 給testFindById()添加測試註解符
- 將單元測試JUnit4添加到類路徑,才能使用測試註解符
@Test
- 將鼠標移到
@Test
,按<Alt>+<Enter>
組合鍵,彈出快捷菜單,選擇第一項Add 'JUnit4' to classpath
- 執行單元測試方法testFindById()
- 查看添加到類路徑的JUnit4
- 編寫單元測試方法testFindById()代碼
- 運行測試方法testFindById(),查看結果
(2)編寫測試方法testUpdate()
- 運行測試方法testUpdate(),查看結果
由此可見,CollegeDaoImpl的兩個方法都通過了單元測試,其實多個測試方法可以一起進行測試,這樣做測試效率更高。
(3)同時運行多個測試方法
(4)修改完善測試代碼
- 兩個測試方法的第一行代碼都是一樣的,因此可以提取出來
- 在每個單元測試之前都要執行的代碼,我們可以將代碼放在一個方法裏面,但是加上一個註解符
@Before
即可。 - 在每個單元測試之後都要執行的代碼,我們可以將代碼放在一個方法裏面,但是加上一個註解符
@After
即可。 - 添加測試前與測試後要執行的代碼
- 運行測試方法testFindById(),查看結果
- 運行測試方法testUpdate(),查看結果
2、創建狀態數據訪問接口實現類
- 創建狀態數據訪問接口實現類StatusDaoImpl
package net.hw.student.dao.impl;
import net.hw.student.bean.Status;
import net.hw.student.dao.StatusDao;
import net.hw.student.dbutil.ConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 功能:狀態數據訪問接口實現類
* 作者:華衛
* 日期:2020年06月05日
*/
public class StatusDaoImpl implements StatusDao {
@Override
public Status findById(int id) {
// 聲明狀態對象
Status status = null;
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "SELECT * FROM t_status WHERE id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setInt(1, id);
// 5. 執行SQL查詢,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
// 實例化狀態
status = new Status();
// 利用當前記錄字段值去設置狀態對象的屬性
status.setId(rs.getInt("id"));
status.setCollege(rs.getString("college"));
status.setVersion(rs.getString("version"));
status.setAuthor(rs.getString("author"));
status.setTelephone(rs.getString("telephone"));
status.setAddress(rs.getString("address"));
status.setEmail(rs.getString("email"));
}
// 7. 關閉預備語句對象
pstmt.close();
// 8. 關閉結果集對象
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回狀態對象
return status;
}
@Override
public int update(Status status) {
// 定義更新記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "update t_status set college = ?, version = ?, author = ?,"
+ " telephone = ?, address = ?, email = ? where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, status.getCollege());
pstmt.setString(2, status.getVersion());
pstmt.setString(3, status.getAuthor());
pstmt.setString(4, status.getTelephone());
pstmt.setString(5, status.getAddress());
pstmt.setString(6, status.getEmail());
pstmt.setInt(7, status.getId());
// 5. 執行更新操作,更新記錄
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回更新記錄數
return count;
}
}
單元測試:對StatusDaoImpl進行單元測試
- 在net.hw.student.test包裏創建測試類TestStatusDaoImpl
(1)編寫測試方法testFindById()
- 運行testFindById()方法,查看結果
(2)編寫測試方法testUpdate()
- 運行testUpdate()方法,查看結果
- 有些同學,在測試更新方法時,拋出MySQLSyntaxErrorException,如下圖所示:
要學會看錯誤提示信息,這對於我們開發程序相當重要,提示在telephone = '13845456780’附近存在MySQL句法錯誤,因此,我們要去看源碼進行調試,解決這個錯誤。
3、學生數據訪問接口實現類
- 學生數據訪問接口實現類StudentDaoImpl
package net.hw.student.dao.impl;
import net.hw.student.bean.Student;
import net.hw.student.dao.StudentDao;
import net.hw.student.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* 功能:學生數據訪問接口實現類
* 作者:華衛
* 日期:2020年06月05日
*/
public class StudentDaoImpl implements StudentDao {
/**
* 插入學生記錄
*
* @param student
* @return 插入記錄數
*/
@Override
public int insert(Student student) {
// 定義插入記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "insert into t_student (id, name, sex, age, department, class, telephone)"
+ " values (?, ?, ?, ?, ?, ?, ?)";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, student.getId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getSex());
pstmt.setInt(4, student.getAge());
pstmt.setString(5, student.getDepartment());
pstmt.setString(6, student.getClazz());
pstmt.setString(7, student.getTelephone());
// 5. 執行SQL,返回插入記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回插入記錄數
return count;
}
/**
* 按學號刪除學生記錄
*
* @param id
* @return 刪除記錄數
*/
@Override
public int deleteById(String id) {
// 定義刪除記錄數
int count = 0;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "delete from t_student where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, id);
// 5. 執行SQL,返回刪除記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回刪除記錄數
return count;
}
/**
* 按班級刪除學生記錄
*
* @param clazz
* @return 刪除記錄數
*/
@Override
public int deleteByClass(String clazz) {
// 定義刪除記錄數
int count = 0;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "delete from t_student where class = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, clazz);
// 5. 執行SQL,返回刪除記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回刪除記錄數
return count;
}
/**
* 按系部刪除學生記錄
*
* @param department
* @return 刪除記錄數
*/
@Override
public int deleteByDepartment(String department) {
// 定義刪除記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "delete from t_student where department = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, department);
// 5. 執行SQL,返回刪除記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回刪除記錄數
return count;
}
/**
* 更新學生記錄
*
* @param student
* @return 更新記錄數
*/
@Override
public int update(Student student) {
// 定義更新記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "update t_student set name = ?, sex = ?, age = ?,"
+ " department = ?, class = ?, telephone = ? where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getSex());
pstmt.setInt(3, student.getAge());
pstmt.setString(4, student.getDepartment());
pstmt.setString(5, student.getClazz());
pstmt.setString(6, student.getTelephone());
pstmt.setString(7, student.getId());
// 5. 執行SQL,返回更新記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回更新記錄數
return count;
}
/**
* 按學號查詢學生記錄
*
* @param id
* @return 學生實體
*/
@Override
public Student findById(String id) {
// 聲明學生對象
Student student = null;
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_student where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, id);
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
// 創建學生實體
student = new Student();
// 利用當前記錄各字段值設置學生實體屬性
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDepartment(rs.getString("department"));
student.setClazz(rs.getString("class"));
student.setTelephone(rs.getString("telephone"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學生對象
return student;
}
/**
* 按姓名查詢學生記錄
*
* @param name
* @return 學生列表
*/
@Override
public List<Student> findByName(String name) {
// 聲明學生列表
List<Student> students = new ArrayList<Student>();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_student where name like ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, name + "%");
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 遍歷結果集
while (rs.next()) {
// 創建學生實體
Student student = new Student();
// 利用當前記錄各字段值設置學生實體屬性
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDepartment(rs.getString("department"));
student.setClazz(rs.getString("class"));
student.setTelephone(rs.getString("telephone"));
// 將實體添加到學生列表
students.add(student);
}
// 7. 關閉結果集
rs.close();
// 8. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學生列表
return students;
}
/**
* 按班級查詢學生記錄
*
* @param clazz
* @return 學生列表
*/
@Override
public List<Student> findByClass(String clazz) {
// 聲明學生列表
List<Student> students = new ArrayList<Student>();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_student where class like ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, clazz + "%");
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 遍歷結果集
while (rs.next()) {
// 創建學生實體
Student student = new Student();
// 利用當前記錄各字段值設置學生實體屬性
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDepartment(rs.getString("department"));
student.setClazz(rs.getString("class"));
student.setTelephone(rs.getString("telephone"));
// 將實體添加到學生列表
students.add(student);
}
// 7. 關閉結果集
rs.close();
// 8. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學生列表
return students;
}
/**
* 按系部查詢學生記錄
*
* @param department
* @return 學生列表
*/
@Override
public List<Student> findByDepartment(String department) {
// 聲明學生列表
List<Student> students = new ArrayList<Student>();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_student where department like ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, department + "%");
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 遍歷結果集
while (rs.next()) {
// 創建學生實體
Student student = new Student();
// 利用當前記錄各字段值設置學生實體屬性
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDepartment(rs.getString("department"));
student.setClazz(rs.getString("class"));
student.setTelephone(rs.getString("telephone"));
// 將實體添加到學生列表
students.add(student);
}
// 7. 關閉結果集
rs.close();
// 8. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學生列表
return students;
}
/**
* 查詢全部學生記錄
*
* @return 學生列表
*/
@Override
public List<Student> findAll() {
// 聲明學生列表
List<Student> students = new ArrayList<Student>();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_student";
try {
// 3. 創建語句對象
Statement stmt = conn.createStatement();
// 4. 執行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 5. 遍歷結果集
while (rs.next()) {
// 創建學生實體
Student student = new Student();
// 利用當前記錄各字段值設置學生實體屬性
student.setId(rs.getString("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDepartment(rs.getString("department"));
student.setClazz(rs.getString("class"));
student.setTelephone(rs.getString("telephone"));
// 將實體添加到學生列表
students.add(student);
}
// 6. 關閉結果集
rs.close();
// 7. 關閉語句對象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回學生列表
return students;
}
/**
* 按性別統計學生人數
*
* @return 統計結果向量
*/
@Override
public Vector findRowsBySex() {
// 定義行集向量
Vector rows = new Vector();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select sex as '性別', count(*) as '人數'"
+ " from t_student group by sex order by sex desc";
try {
// 3. 創建語句對象
Statement stmt = conn.createStatement();
// 4. 執行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 5. 遍歷結果集
while (rs.next()) {
// 定義當前行向量
Vector<String> currentRow = new Vector();
// 利用當前記錄字段值設置當前行向量的元素值
currentRow.addElement(rs.getString("性別"));
currentRow.addElement(rs.getInt("人數") + "");
// 將當前行向量添加到行集向量
rows.addElement(currentRow);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回行集向量
return rows;
}
/**
* 按班級統計學生人數
*
* @return 統計結果向量
*/
@Override
public Vector findRowsByClass() {
// 定義行集向量
Vector rows = new Vector();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select class as '班級', count(*) as '人數'"
+ " from t_student group by class order by class desc";
try {
// 3. 創建語句對象
Statement stmt = conn.createStatement();
// 4. 執行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 5. 遍歷結果集
while (rs.next()) {
// 定義當前行向量
Vector<String> currentRow = new Vector();
// 利用當前記錄字段值設置當前行向量的元素值
currentRow.addElement(rs.getString("班級"));
currentRow.addElement(rs.getInt("人數") + "");
// 將當前行向量添加到行集向量
rows.addElement(currentRow);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回行集向量
return rows;
}
/**
* 按系部統計學生人數
*
* @return 統計結果向量
*/
@Override
public Vector findRowsByDepartment() {
// 定義行集向量
Vector rows = new Vector();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select department as '系部', count(*) as '人數'"
+ " from t_student group by department order by department desc";
try {
// 3. 創建語句對象
Statement stmt = conn.createStatement();
// 4. 執行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 5. 遍歷結果集
while (rs.next()) {
// 定義當前行向量
Vector<String> currentRow = new Vector();
// 利用當前記錄字段值設置當前行向量的元素值
currentRow.addElement(rs.getString("系部"));
currentRow.addElement(rs.getInt("人數") + "");
// 將當前行向量添加到行集向量
rows.addElement(currentRow);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回行集向量
return rows;
}
}
單元測試:對StudentDaoImpl進行單元測試
- 在net.hw.student.test包裏創建測試類TestStudentDaoImpl
(1)編寫測試方法testInsert()
- 運行該測試方法,查看結果
- 可以打開數據表,查看插入的新記錄
(2)編寫測試方法testDeleteById()
- 運行該測試方法,查看結果
- 打開數據表,查看先前插入的記錄【鄧聰】是否被刪除
- 說明:最後一條記錄又變成【李玉仙】,插入的新記錄【鄧聰】已被刪除
(3)編寫測試方法testDeleteByClass()
- 運行該測試方法,查看結果
- 同學們,不妨打開學生表,查看是否刪除成功
- 打開NaviCat,運行student.sql腳本,恢復數據。
(4)編寫測試方法testFindByName()
- 運行該測試方法,查看結果
- 修改待查學生的姓名
- 運行該測試方法,查看結果
- 查找所有姓“李”的學生記錄,修改查找目標
- 運行該測試方法,查看結果
(5)編寫測試方法testFindAll()
- 運行該測試方法,查看結果
(6)編寫測試方法testFindRowsBySex()
- 運行該測試方法,查看結果
獨立完成剩餘方法的測試任務
(1)編寫測試方法testDeleteByDepartment()
(2)編寫測試方法testUpdate()
(3)編寫測試方法testFindById()
(4)編寫測試方法testFindByClass()
(5)編寫測試方法testFindByDepartment()
(6)編寫測試方法testFindRowsByClass()
(7)編寫測試方法testFindRowsByDepartment()
4、創建用戶數據訪問接口實現類
- 創建用戶數據訪問接口實現類UserDaoImpl
package net.hw.student.dao.impl;
import net.hw.student.bean.User;
import net.hw.student.dao.UserDao;
import net.hw.student.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 功能:用戶數據訪問接口實現類
* 作者:華衛
* 日期:2020年06月05日
*/
public class UserDaoImpl implements UserDao {
/**
* 插入用戶記錄
*
* @param user
* @return 插入記錄數
*/
@Override
public int insert(User user) {
// 定義插入記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "insert into t_user (username, password, telephone, register_time)"
+ " values (?, ?, ?, ?)";
// 不允許用戶表裏插入兩條用戶名相同的記錄
if (!isUsernameExisted(user.getUsername())) {
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getTelephone());
pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
// 5. 執行SQL,返回插入記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
}
// 返回插入記錄數
return count;
}
/**
* 按id刪除用戶記錄
*
* @param id
* @return 刪除記錄數
*/
@Override
public int deleteById(int id) {
// 定義刪除記錄數
int count = 0;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "delete from t_user where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setInt(1, id);
// 5. 執行SQL,返回刪除記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回刪除記錄數
return count;
}
/**
* 更新用戶記錄
*
* @param user
* @return 更新記錄數
*/
@Override
public int update(User user) {
// 定義更新記錄數
int count = 0;
// 1. 獲得數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "update t_user set username = ?, password = ?, telephone = ?,"
+ " register_time = ? where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getTelephone());
pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
pstmt.setInt(5, user.getId());
// 5. 執行SQL,返回更新記錄數
count = pstmt.executeUpdate();
// 6. 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回更新記錄數
return count;
}
/**
* 按id查詢用戶
*
* @param id
* @return 用戶實體
*/
@Override
public User findById(int id) {
// 聲明用戶對象
User user = null;
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_user where id = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setInt(1, id);
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
// 創建用戶實體
user = new User();
// 利用當前記錄各字段值設置用戶實體屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回用戶對象
return user;
}
/**
* 查詢所有用戶
*
* @return 用戶列表
*/
@Override
public List<User> findAll() {
// 聲明用戶列表
List<User> users = new ArrayList<User>();
// 1. 獲取數據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_user";
try {
// 3. 創建語句對象
Statement stmt = conn.createStatement();
// 4. 執行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 5. 遍歷結果集
while (rs.next()) {
// 創建用戶實體
User user = new User();
// 利用當前記錄各字段值設置用戶實體屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
// 將實體添加到用戶列表
users.add(user);
}
// 6. 關閉結果集
rs.close();
// 7. 關閉語句對象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回用戶列表
return users;
}
/**
* 用戶登錄
*
* @param username
* @param password
* @return 登錄用戶實體
*/
@Override
public User login(String username, String password) {
// 聲明用戶對象
User user = null;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_user where username = ? and password = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, username);
pstmt.setString(2, password);
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
// 實例化用戶
user = new User();
// 利用當前記錄各字段值設置用戶實體屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回用戶對象
return user;
}
@Override
public boolean isUsernameExisted(String username) {
// 定義存在與否變量
boolean existed = false;
// 1. 獲取數據庫連接
Connection conn = ConnectionManager.getConnection();
// 2. 定義SQL字符串
String strSQL = "select * from t_user where username = ?";
try {
// 3. 創建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4. 設置佔位符的值
pstmt.setString(1, username);
// 5. 執行SQL,返回結果集
ResultSet rs = pstmt.executeQuery();
// 6. 判斷結果集是否有記錄
if (rs.next()) {
existed = true;
}
// 7. 關閉預備語句對象
pstmt.close();
// 8. 關閉結果集對象
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉數據庫連接
ConnectionManager.closeConnection(conn);
}
// 返回存在與否變量
return existed;
}
}
單元測試:對UserDaoImpl進行單元測試
- 在net.hw.student.test包裏創建測試類TestUserDaoImpl
(1)編寫測試方法testFindById()
- 運行該測試方法,查看結果
(2)編寫測試方法testLogin()
- 運行該測試方法,查看結果
- 修改用戶名和密碼
- 運行該測試方法,查看結果
(3)編寫測試方法testIsUsernameExisted()
- 運行該測試方法,查看結果
- 修改用戶名,改成用戶表裏有的用戶名【王霞】
- 運行該測試方法,查看結果
(4)編寫測試方法testInsert()
- 運行該測試方法,查看結果
- 再次運行該測試方法,查看結果
- 因爲不允許同名用戶插入,所以用戶記錄插入失敗。