TestCollegeDaoImpl的代码
package net.hlj.student.test;
import net.hlj.student.bean.College;
import net.hlj.student.dao.CollegeDao;
import net.hlj.student.dao.impl.CollageDaoImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
-
功能:测试学校数据访问接口实现类
-
姓名:黄丽娟
-
日期:2019年6月27日
*/
public class TestCollegeDaoImpl {
//创建学校数据访问对象
CollegeDao dao = new CollageDaoImpl();@Before
public void beforeTest(){
System.out.println(“温馨提示:单元测绘开始咯~”);
}@After
public void afterTest(){
System.out.println(“温馨提示:单元测试结束咯~”);
}@Test
public void testFindById(){
//调用学校数据访问对象的查询方法
College college = dao.findById(1);
//输出学校对象
System.out.println(college);}
@Test
public void testUpadate(){
//调用学校数据访问对象的查询方法
College college = dao.findById(1);
//修改学校信息
college.setPresident(“黄丽娟”);
//调用学校数据访问对象的更新方法
int count = dao.update(college);
//判断是否更新成功
if (count > 0) {
System.out.println(“学校记录更新成功!”);
System.out.println(“新校长:” + dao.findById(1).getPresident());
}else{
System.out.println(“学校记录更新失败!”);
}}
}
再运行测试方法testFindById(),结果如下:
状态数据访问接口实现类StatusDaoImpl
![在这里插入图片描述]
package net.hlj.student.dao.impl;
import net.hlj.student.bean.Status;
import net.hlj.student.dao.StatusDao;
import net.hlj.student.dbutil.ConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
- 功能:状态数据访问接口实现类
- 姓名:黄丽娟
- 日期:2019年6月28日
*/
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;
}
}
在net.hw.student.test包里创建测试类TestStatusDaoImpl:
编写测试方法testFindById():运行testFindById()方法,结果如下:
编写测试方法testUpdate():运行testUpdate()方法,结果如下:
要学会看错误提示信息,这对于我们开发程序相当重要,提示在telephone = '13845456780’附近存在MySQL句法错误,因此,我们要去看源码进行调试,解决这个错误。
学生数据访问接口实现类StudentDaoImpl
package net.hlj.student.dao.impl;
import net.hlj.student.bean.Student;
import net.hlj.student.dao.StudentDao;
import net.hlj.student.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
- 功能:学生数据访问接口实现类
- 作者:黄丽娟
- 日期:2019年6月28日
*/
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;
}
@Override
public Vector findRowsByclass() {
return null;
}
/**
* 按班级统计学生人数
*
* @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 = ((Statement) 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;
}
}
在net.hw.student.test包里创建测试类TestStudentDaoImpl:
编写测试方法testDeleteById():
编写测试方法testDeleteByClass():
编写测试方法testFindByName():
创建测试方法testFindAll():
创建测试方法testFindRowsBySex():
用户数据访问接口实现类UserDaoImpl
package net.hlj.student.dao.impl;
import net.hlj.student.bean.User;
import net.hlj.student.dao.UserDao;
import net.hlj.student.dbutil.ConnectionManager;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
-
功能:用户数据访问接口实现类
-
作者:黄丽娟
-
日期:2019年6月29日
/
public abstract 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 (?,?,?,?)";
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.getRegister_time().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.getRegister_time().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.setRegister_time(rs.getTimestamp("register_time")); } }catch (SQLException e) { e.printStackTrace(); } finally { //关闭数据库连接 ConnectionManager.closeConnection(conn); } //返回用户对象 return user;
}
/**
- 查询所以用户
- @return 用户列表
*/
@Override
public List findAll() {
//声明用户列表
List users = new ArrayList();// 1. 获取数据库连接对象 Connection conn = ConnectionManager.getConnection(); // 2. 定义SQL字符串 String strSQL = "select * from t_user"; try { // 3. 创建预备语句对象 PreparedStatement pstmt = conn.prepareStatement(strSQL); //4.执行SQL,返回结果集 ResultSet rs = pstmt.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.setRegister_time(rs.getTimestamp("register_time")); // 将实体添加到用户列表 users.add(user); } // 6. 关闭结果集 rs.close(); // 7. 关闭语句对象 pstmt.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.setRegister_time(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 usename = ?"; 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 false;
}
} -
在net.hw.student.test包里创建测试类TestUserDaoImpl:
package net.hlj.student.test;
import net.hlj.student.bean.User;
import net.hlj.student.dao.UserDao;
import net.hlj.student.dao.impl.UserDaoImpl;
import org.junit.Test;
import java.util.Date;
/**
- 功能:测试用户数据访问接口实现类
- 作者:黄丽娟
- 日期:2019年6月29日
*/
public class TestUserDaoImpl {
//定义用户数据访问对象
UserDao dao = new UserDaoImpl() {
};
@Test
public void testFindById() {
//调用用户数据访问对象的查找方法
User user = dao.findById(1);
//输出用户对象
System.out.println(user);
}
@Test
public void testLogin() {
String username, password;
username = “admin”;
password = “12345”;
//调用用户数据访问对象的登录方法
User user = dao.login(username, password);
//判断用户登录是否成功
if (user != null) {
System.out.println(“恭喜,用户名与密码正确,登录成功!”);
} else {
System.out.println(“遗憾,用户名或密码错误,登录失败!”);
}
}
@Test
public void testInsert() {
//定义用户对象
User user = new User();
//设置用户属性
user.setUsername(“吴彦文”);
user.setPassword(“34567”);
user.setTelephone(“15823234590”);
user.setRegister_time(new Date());
//调用用户树访问对象的插入方法
int count = dao.insert(user);
//判断用户记录是否插入成功
if (count > 0) {
System.out.println(“恭喜,用户记录插入成功!”);
System.out.println(“遗憾,用户记录插入失败!”);
} else {
System.out.println(“遗憾,用户记录插入失败!”);
}
}
@Test
public void testIsUsernameExisted() {
//定义用户名
String usrname = “李刚”;
//调用用户数据访问对象的用户名存在与否方法
boolean result = dao.isUsernameExisted(usrname);
//判断用户名是否存在
if (result) {
System.out.println(“温馨提示:[” + usrname + “]已存在,不可用此名注册!”);
} else {
System.out.println(“温馨提示:[” + usrname + “]不存在,可用此名注册!”);
}
}
}
解决思路:在UserDao添加一个判断用户名是否存在的方法,如果存在,返回真,否则返回假。
package net.hlj.student.dao.impl;
import net.hlj.student.bean.User;
import net.hlj.student.dao.UserDao;
import net.hlj.student.dbutil.ConnectionManager;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
-
功能:用户数据访问接口实现类
-
作者:黄丽娟
-
日期:2019年6月29日
/
public abstract 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 (?,?,?,?)";
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.getRegister_time().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.getRegister_time().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.setRegister_time(rs.getTimestamp("register_time")); } }catch (SQLException e) { e.printStackTrace(); } finally { //关闭数据库连接 ConnectionManager.closeConnection(conn); } //返回用户对象 return user;
}
/**
- 查询所以用户
- @return 用户列表
*/
@Override
public List findAll() {
//声明用户列表
List users = new ArrayList();// 1. 获取数据库连接对象 Connection conn = ConnectionManager.getConnection(); // 2. 定义SQL字符串 String strSQL = "select * from t_user"; try { // 3. 创建预备语句对象 PreparedStatement pstmt = conn.prepareStatement(strSQL); //4.执行SQL,返回结果集 ResultSet rs = pstmt.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.setRegister_time(rs.getTimestamp("register_time")); // 将实体添加到用户列表 users.add(user); } // 6. 关闭结果集 rs.close(); // 7. 关闭语句对象 pstmt.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.setRegister_time(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 usename = ?"; 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 false;
}
} -