1)Java基本语法
(2)Java流程控制(顺序、选择、循环)
(3)Java数据库编程(JDBC)
(4)Java面向对象编程(封装、继承、多态、接口)
(5)Java核心API(List、Vector……)
(6)MySQL数据库操作
(7)MVC模式分层架构(M:模型层、V:视图层、C:控制层)
8)单元测试(JUnit4: @Test, @Before, @After)
| |View(视图)–pc端,安卓客户端 |
|-Controll(控制层)–|
| Model(模型层)–DB,DAO,Service |
0、创建数据库及表
数据库student中有4个表:t_student、t_user、t_college、t_status
(1)t_college表
(2)t_status表]
(3)t_student表
(4)t_user表
数据库脚本(student.sql)
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('10080301', '陈刚', '男', '20', '外语系', '10英教1班', '13934345678');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('10080302', '李煜', '男', '19', '外语系', '10英教1班', '13989896656');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('10080303', '钟磊', '女', '20', '外语系', '10英教1班', '13867674534');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('10080804', '吴欣', '女', '20', '外语系', '10英教1班', '13956561123');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11040201', '李阳', '男', '19', '建筑系', '11建工1班', '13978561130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11040202', '陈洁', '女', '20', '建筑系', '11建工1班', '13978564530');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11040203', '吴刚', '男', '19', '建筑系', '11建工1班', '13978234530');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11040204', '吴灵', '女', '19', '建筑系', '11建工1班', '13878234530');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080301', '武陵', '男', '19', '外语系', '11英教1班', '13567671130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080302', '王菲', '女', '20', '外语系', '11英教1班', '13567981123');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080303', '陈俊', '男', '20', '外语系', '11英教1班', '13945455656');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080304', '向刚', '男', '19', '外语系', '11英教1班', '13978781130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080305', '李文', '女', '20', '外语系', '11英教1班', '13978381130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080306', '吴刚', '男', '19', '外语系', '11英教1班', '15878381130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080307', '陈宇', '男', '20', '外语系', '11英教1班', '12878381130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11080308', '华晨', '男', '19', '外语系', '11英教1班', '13978381130');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11090701', '李强', '男', '20', '信息工程系', '11软件2班', '13890901120');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11090702', '张红', '女', '20', '信息工程系', '11软件2班', '13834341128');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11090703', '文雯', '女', '19', '信息工程系', '11软件2班', '13956756567');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('11090704', '吴刚', '男', '19', '信息工程系', '11软件2班', '13844455678');
INSERT INTO `t_student`(`id`, `name`, `sex`, `age`, `department`, `class`, `telephone`) VALUES ('15012456', '李玉仙', '女', '18', '信息工程系', '15软件1班', '15890904567');
t_college脚本
INSERT INTO `t_college` VALUES (1, '泸州职业技术学院', '贺元成', '2003-04-23 00:00:00', '3152608', 'lzy2003@lzy.com', '泸州市江阳区瓦窑坝',
' 泸州职业技术学院是经四川省人民政府批准、国家教育部备案的综合性公办普通高等学校,占地面积655.1亩,按照新校区建设规划占地面积将达到1500亩左右,
是省级园林式单位、市级文明单位。2011年批准为四川省示范高职院校建设单位。 \n\n 学院现有商学院、机械工程系、电子工程系、建筑工程系、信息工程系、
人文社科系、外语系、艺术系、基础部、思政教研部等十个教学单位。开办机械、土建、商务、电子信息、生物工程、财经、旅游、文化教育等类别的高职专科教育专业35个,
拥有各类在校生8000多人。\n \n 一、悠久的办学历史和鲜明的办学特色\n\n 学院荟萃着光荣传统、优良校风和丰富的高等教育办学经验,其前身可以追溯
到创建于1901年的川南经纬学堂。学院坚持“瞄准社会需求,培养创业技能,造就优秀人才”的办学理念和“传承百年文化、服务地方产业、助推区域发展”的办学思路,弘扬
“自强不息,勤奋敬业”校训精神,实施“质量立校,文化塑校,人才强校”发展战略,形成了“四合四共”(合作办学、合作育人、合作就业、合作发展,人才共育、过程共管、
成果共享、责任共担)的“政园企校”四方共建机制,逐步完善了“五位一体”(校地发展共生一体、校企合作产教一体、专业产业对接一体、人才培养工学一体、技术研发校企
一体)办学模式,主动适应地方经济社会发展需要,以服务为宗旨、就业为导向,走产学研结合之路,培养高素质技能型人才。\n\n 二、雄厚的师资力量和完备的
教学设施\n\n 学院现有教职工509人,其中专任教师388人;专任教师中,教授9人,副教授83人,高级工程师、高级实验师等其他高级职称9人,具有博士、硕士学位
人员201人,长驻外籍教师2人;拥有省级突出贡献专家1人,省级学术和技术带头人后备人选1人;市级学术和技术带头人3人,市级学术和技术带头人后备人选2人,泸州市
拔尖人才3人,泸州市“知名教师”13人;学院学科带头人7人,专业带头人19人,中青年骨干教师41人;程序员、工程师、建造师等各类“双师型”教师182人;省级优秀教学团队
2个,院级优秀教学团队11个;建立了由200多名行业企业专家、经理、技术能手组成的兼职教师资源库。\n\n 学院拥有现代化图书馆藏书42.5万余册,数字资源10TB;
建有人文艺术中心、工程实训中心、玉阶素质教育基地、标准田径运动场、网球场等完备的教育教学设施;建有中央财政支持的电工电子与自动化国家级实训基地,拥有实验室、
实训室178间,生产性实训基地6个,校外实习实训基地93个。\n\n 三、丰硕的科研成果和良好的社会服务\n\n 学院完成科技部项目1项,现有省级项目27项,
市级项目104项,院级项目112个,横向委托项目22项;获省级教学成果奖1项、省级教育科研成果奖16项、市级科技进步奖5项、市级哲学社会科学成果奖33项;院级教学成果奖
11项;教师共发表核心期刊论文160余篇,其中《机械工程学报》等一级期刊论文6篇,EI和ISTP收录11篇;教师获专利10项;拥有省级精品课程5门,省级教改项目9项,省级
精品教材建设项目1项;院级精品课程51门,院级教改项目93项。\n \n 学院是国家职业技能鉴定站的挂牌单位,能承担机械及制造、电子电工、建筑、管理及服务、
计算机及信息、教师职业技能等8大类别的68种职业技能鉴定。学院立足泸州、面向四川、辐射滇黔渝,积极开展继续教育和职业培训,是“省委组织部大学生村干部创业培训
基地”、“四川省乡村旅游实用人才开发示范单位”、“泸州市白酒产业高技能人才培养基地”、“泸州市装备制造业高技能人才培养基地”、“泸州市现代服务业高技能人才培养基地”、
“市委组织部农村基层干部培训基地”。近年来,承担各类社会培训200多项近30000人次。\n\n 四、优异的竞赛成绩和畅通的就业渠道\n\n 2007年以来,学院
学生先后在Honda中国节能竞技大赛、全国电子专业人才设计与技能大赛、全国高校市场营销大赛、全国旅游院校服务技能大赛等国家级技能大赛和四川省大学生电子设计大赛、
四川省大学生旅游艺术设计大赛等省级技能大赛中获奖270余人次。\n \n 我院与泸州老窖集团、四川郎酒集团、四川邦立重机有限责任公司、宜宾五粮液集团、
宜宾丝丽雅集团、Intel公司、富士康科技集团、康佳集团、格力电器、中铁五局、中建八局、华西集团等1000多家企业开展就业合作关系,建立起了以泸州及成渝经济区为主,
包含珠三角、长三角地区在内的就业网络,形成了畅通的就业渠道,为毕业生提供可靠的就业保障,毕业生就业率连续6年保持在97%以上。');
t_user表
INSERT INTO `t_user` VALUES (1, '李刚', '123', '15888781123', '2012-05-21 09:26:10');
INSERT INTO `t_user` VALUES (2, '王霞', '123244', '13990901140', '2012-06-08 12:49:27');
INSERT INTO `t_user` VALUES (3, '段誉', '123', '12345678907', '2012-06-08 12:50:23');
INSERT INTO `t_user` VALUES (4, 'admin', '12345', '13989891123', '2012-06-08 16:52:26');
INSERT INTO `t_user` VALUES (5, '李红', '222222', '15888781123', '2012-06-08 16:53:17');
INSERT INTO `t_user` VALUES (6, 'browser', '11111', '13853452232', '2012-06-11 12:55:46');
INSERT INTO `t_user` VALUES (7, 'operater', '22222', '1234567890', '2012-06-11 12:55:36');
INSERT INTO `t_user` VALUES (8, '王平', '33333', '1234500000', '2012-06-11 12:57:54');
t_status
INSERT INTO `t_status` VALUES (1, '泸职院', 'V1.0', '华大哥', '15892921170', '泸职院信息工程系', '2547073233@qq.com');
数据插入完后,就开始编写代码。
1,创建java项目
2,在项目里添加文件夹help,images,lib
3,在lib里面添加连接数据库的jar包
作为库添加到项目里(Add as Library…)
4.在images添加图片
这里的话随便什么照片,只要名称是上面的名称就可以了
5,创建实体类(与数据库一一对应)
首先在src目录里创建net.hw.student.bean包:
hw可改为哦、名字的缩写
然后依次创建四个实体类:College、Status、Student与User,分别对应t_college表、t_status表、t_student表与t_user表。
(1)学校实体Colleg
这里前面的,是自己写,后面的可以用快捷键敲出
alt+insert弹出生成菜单,选择set和get
下面的那个选toS…
package net.wlq.student.bean;
import java.sql.Date;
/**
* 功能:学校实体类
* 作者:王亮琴
* 日期:2019年6月26日
*/
public class College {
/**
* 学校标志符
*/
private int id;
/**
* 学校名称
*/
private String name;
/**
*
*/
private String president;
/**
*校长
*/
private Date starTime;
/**
* 建校时间
*/
private String telephone;
/**
* 联系电话
*/
private String email;
/**
* 电子邮件
*/
private String address;
/**
* 通讯地址
*/
private String profile;
/**
*
* 学校简介
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPresident() {
return president;
}
public void setPresident(String president) {
this.president = president;
}
public Date getStarTime() {
return starTime;
}
public void setStarTime(Date starTime) {
this.starTime = starTime;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
@Override
public String toString() {
return "College{" +
"id=" + id +
", name='" + name + '\'' +
", president='" + president + '\'' +
", starTime=" + starTime +
", telephone='" + telephone + '\'' +
", email='" + email + '\'' +
", address='" + address + '\'' +
", profile='" + profile + '\'' +
'}';
}
}
(2)状态实体Status
package net.wlq.student.bean;
/**
* 功能:Status实体类
* 作者:王亮琴
* 日期:2019年6月26日
*/
public class Status {
/**
* 标识符
*/
private int id;
/**
* 校名
*/
private String college;
/**
* 版本
*/
private String version;
/**
* 作者
*/
private String author;
/**
* 联系电话
*/
private String telephone;
/**
* 通信地址
*/
private String address;
/**
* 电子邮箱
*/
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Status{" +
"id=" + id +
", college='" + college + '\'' +
", version='" + version + '\'' +
", author='" + author + '\'' +
", telephone='" + telephone + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
3)学生实体Student
package net.wlq.student.bean;
public class Student {
/**
* 学号
*/
private String id;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private int age;
/**
* 系部
*/
private String department;
/**
* 班级
*/
private String clazz;
/**
* 联系电话
*/
private String telephone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", department='" + department + '\'' +
", clazz='" + clazz + '\'' +
", telephone='" + telephone + '\'' +
'}';
}
}
(4)用户实体User
package net.wlq.student.bean;
import java.util.Date;
public class User {
/**
* 用户标识符
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 联系电话
*/
private String telephone;
/**
* 注册时间
*/
private Date registerTime;
public int getId() {
return id;
}
public void setId(int 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;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
'}';
}
}
7、在建一个包dbutil,在里面创建一个数据库连接管理类ConnectionManager
类ConnectionManager
package net.wlq.student.dbutil;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 功能:数据库连接管理
* 作者:王亮琴
* 日期:2019年6月26日
*/
public class ConnectionManager {
/**
* 数据库驱动程序
*
*/
private static final String DRIVER ="com.mysql.jdbc.Driver";
/**
* 数据库统一资源标识符
*/
private static final String URL ="jdbc:mysql://localhost:3306/student";
/**
* 数据库用户
*/
private static final String USER="root";
/**
* 数据库密码
*/
private static final String PASSWORD="1";
/**
* 私有化构造方法,拒绝实例化
*/
private ConnectionManager(){
}
/**
* 获取数据库连接静态方法
*
* @return 数据库连接对象
*/
public static Connection getConnection(){
Connection conn = null;
try {
// 安装数据库驱动程序
Class.forName(DRIVER);
// 获取数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
//返回数据库连接
return conn;
}
/**
* 关闭数据库连接静态方法
* conn
*/
public static void closeConnection(Connection conn) {
//判断数据库连接是否为空
if (conn != null){
try {
// 判断连接是否未关闭
if (!conn.isClosed()) {
// 关闭数据库连接
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 主方法:测试两个静态方法
*
* @param args
*/
public static void main(String[] args) {
// 获取数据库连接
Connection conn = getConnection();
// 判断数据库连接是否成功
if (conn != null) {
JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");
} else {
JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");
}
// 关闭数据库连接
closeConnection(conn);
}
}
这里要注意的是你们的数据库名称里密码和我的不一样哦,不要看都不看就复制下来
运行程序,测试数据库连接是否成功:
数据库连接成功
8,在net.wlq.student包中再建一个包叫bao,在bao里面建四个数据库访问接口
在学校数据访问接口CollegeDao中写入
package net.wlq.student.dao;
import net.wlq.student.bean.College;
/**
* 功能:学校数据访问接口
* 作者:王亮琴
* 日期:2019年6月27日
*/
public interface CollegeDao {
College findById(int id);
int update(College college);
}
在这里要注意的是College不要写成CollegeDao,因为这个包后面会建,可能不小心会混淆。如果你写成了CollegeDao到写这里的时候就会报错
所以不要写错哦,不然不好找错误。
(2)状态数据访问接口StatusDao
package net.wlq.student.dao;
import net.wlq.student.bean.Status;
/**
* 功能:学校数据访问接口
* 作者:王亮琴
* 日期:2019年6月27日
*/
public interface StatusDao {
Status findById(int id);
int update(Status status);
}
(3)学生数据访问接口StudentDao
package net.wlq.student.dao;
import java.util.List;
import java.util.Vector;
import net.wlq.student.bean.Student;
/**
* 功能:学校数据访问接口
* 作者:王亮琴
* 日期:2019年6月27日
*/
public interface StudentDao {
int insert(Student student);
int deleteById(String id);
int deleteByClass(String clazz);
int deleteByDepartment(String department);
int update(Student student);
Student findById(String id);
List<Student> findByName(String name);
List<Student> findByClass(String clazz);
List<Student> findByDepartment(String department);
List<Student> findAll();
Vector findRowsBySex();
Vector findRowsByClass();
Vector findRowsByDepartment();
}
(4)用户数据访问接口UserDao
package net.wlq.student.dao;
import net.wlq.student.bean.User;
import java.util.List;
/** 功能:学校数据访问接口
* 作者:王亮琴
* 日期:2019年6月27日
*/
public interface UserDao {
int insert(User user);
int deleteById(int id);
int update(User user);
User findById(int id);
List<User> findAll();
User login(String username, String password);
}
数据访问接口实现类
在dao包里创建impl子包,然后在里面创建四个数据访问接口的实现类。
(1)学校数据访问接口实现类CollegeDaoImpl,在这里注意一下大小写
这里会报错但是不影响,按alt+insert选择
在写代码过程中3.创建预备语句对象到最后会报错,这时待写完
就选中错误的语句在窗口Code中选中Surround with…选8try catch…。这样就不报错了
代码如下:
package net.wlq.student.dao.impl;
import net.wlq.student.bean.College;
import net.wlq.student.dao.CollegeDao;
import net.wlq.student.dbutil.ConnectionManager;
import java.sql.*;
/**
* 功能:学校数据访问接口
* 作者:王亮琴
* 日期:2019年6月27日
*/
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.setStarTime(rs.getDate("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.getStarTime().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;
}
}
在net.wlq.student里再创建一个子包test,在里面创建测试类TestCollegeDaoImpl
然后故意去修改College实体类,将toString()给注释掉:
再运行
会发现,x没有看到学校对象的内容,只看到包头+类名@哈希码,原因在于实体类的toString()方法被注释了
如果我们将学校实体类的toString()方法恢复正常则会看到学校对象
然后,编写单元测试testUpdate()方法,运行单元测试方法testUpdate():
在每个单元测试之前都要执行的代码,我们可以将代码放在一个方法里面,但是加上一个注解符@Before即可。
在每个单元测试之后都要执行的代码,我们可以将代码放在一个方法里面,但是加上一个注解符@After即可。
运行测试一下方法testUpdate()
状态数据访问接口实现类StatusDaoImpl
package net.wlq.student.dao.impl;
import net.wlq.student.bean.Status;
import net.wlq.student.dao.StatusDao;
import net.wlq.student.dbutil.ConnectionManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
}
}
在test里面创建测试类TestStatusDaoImpl:
package net.wlq.student.test;
import net.wlq.student.bean.Status;
import net.wlq.student.dao.StatusDao;
import net.wlq.student.dao.impl.StatusDaoImpl;
import org.junit.Test;
public class TestStatusDaoImpl {
@Test
public void testFindById(){
StatusDao dao = new StatusDaoImpl();
Status status = dao.findById(1);
System.out.println(status);
}
@Test
public void testUpdate() {
StatusDao dao =new StatusDaoImpl();
Status status = dao.findById(1);
status.setAuthor("无心剑");
status.setTelephone("13956782456");
status.setEmail("wuxinjian@163.com");
dao.update(status);
status = dao.findById(1);
System.out.println(status);
}
package net.wlq.student.test;
import net.wlq.student.bean.Status;
import net.wlq.student.dao.StatusDao;
import net.wlq.student.dao.impl.StatusDaoImpl;
import org.junit.Test;
public class TestStatusDaoImpl {
@Test
public void testFindById(){
StatusDao dao = new StatusDaoImpl();
Status status = dao.findById(1);
System.out.println(status);
}
@Test
public void testUpdate() {
StatusDao dao =new StatusDaoImpl();
Status status = dao.findById(1);
status.setAuthor("无心剑");
status.setTelephone("13956782456");
status.setEmail("wuxinjian@163.com");
dao.update(status);
status = dao.findById(1);
System.out.println(status);
}
}`
在这里插入代码片`
运行testUpdate()方法,结果如下:
因为我的数据库里没有数据所以为null
学生数据访问接口实现类StudentDaoImpl
package net.wlq.student.dao.impl;
import net.wlq.student.bean.Student;
import net.wlq.student.dao.StudentDao;
import net.wlq.student.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
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;
}
}
这里如果有错的话处理方法都是前面提到过的
创建测试类TestStudentDaoImpl
package net.wlq.student.test;
import net.wlq.student.bean.Student;
import net.wlq.student.dao.StudentDao;
import net.wlq.student.dao.impl.StudentDaoImpl;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
public class TestStudentDaoImpl {
@Test
public void testInsert() {
Student student = new Student();
student.setId(“18101001”);
student.setName(“唐鹏”);
student.setSex(“男”);
student.setAge(19);
student.setDepartment(“信息工程系”);
student.setClazz(“18大数据1班”);
student.setTelephone(“15890674568”);
StudentDao dao = new StudentDaoImpl();
int count = dao.insert(student);
if (count > 0 ) {
System.out.println("恭喜,学生记录插入成功!");
}else {
System.out.println("遗憾,学生记录插入失败!");
}
}
@Test
public void testDeleteById() {
StudentDao dao = new StudentDaoImpl();
String id ="18101001";
int count = dao.deleteById(id);
if (count > 0 ) {
System.out.println("恭喜,学生记录插入成功!");
}else {
System.out.println("遗憾,学生记录插入失败!");
}
}
@Test
public void testDeleteByClass() {
StudentDao dao = new StudentDaoImpl();
String clazz= "11英教1班";
int count = dao.deleteById(clazz);
if(count > 0 ) {
System.out.println("恭喜,[" + clazz + "] 学生记录删除成功!");
}else {
System.out.println("遗憾,[" + clazz + "] 学生记录删除失败!");
}
}
@Test
public void testFindByName() {
StudentDao dao = new StudentDaoImpl();
String name = "狠";
List<Student> students = dao.findByName(name);
if (students.size() > 0 ) {
for (Student student : students) {
System.out.println(student);
}
}else{
System.out.println("温馨提示:查无此人!");
}
}
@Test
public void testFindRowsBySex() {
StudentDao dao = new StudentDaoImpl();
Vector rows = dao.findRowsBySex();
Iterator iterator = rows.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
运行两次该方法会得到
打开NaviCat,运行student.sql脚本,恢复数据。
编写测试方法testFindByName():
如何判断是否找到记录,可以修改代码添加for,else判断语句。
运行该测试方法,结果如下(没添加for,else语句):
添加for,else语句
可以修改学生数据访问对象的姓名,我们可以写一个数据库里没有的姓名,则运行后,结果如下:
创建测试方法testFindRowsBySex():
(4)用户数据访问接口实现类UserDaoImpl,编写测试方法testInsert(),打开用户表,看看是否插入了一条新记录。在UserDao添加一个判断用户名是否存在的方法,如果存在,返回真,否则返回假。
package net.hw.student.dao.impl;
import net.hw.student.bean.Student;
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;
/**
* 功能:用户数据访问接口实现类
* 作者:王亮琴
* 日期:2019年6月30日
*/
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 (?, ?, ?, ?)";
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;
}
}
.test包里创建测试类TestUserDaoImpl:
package net.wlq.student.bean.test;
import net.wlq.student.bean.bean.User;
import net.wlq.student.bean.dao.UserDao;
import net.wlq.student.bean.dao.impl.UserDaoImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.List;
/**
* 测试用户数据访问接口实现类
*/
public class TestUserDaoImpl {
@Before
public void beforeTest() {
System.out.println("单元测试开始了!");
}
@After
public void afterTest() {
System.out.println("单元测试结束了!");
}
@Test
public void testInsert() {
User user = new User();
user.setUsername("AAA");
user.setPassword("456");
user.setTelephone("1564658625");
user.setRegisterTime(new Timestamp(2019-1-1));
UserDao dao = new UserDaoImpl();
int count = dao.insert(user);
if (count > 0) {
System.out.println("恭喜,学生记录插入成功");
}else {
System.out.println("遗憾,学生记录插入失败");
}
}
@Test
public void testDeleteById() {
UserDao dao = new UserDaoImpl();
int count = dao.deleteById(1);
if (count > 0) {
System.out.println("恭喜,删除记录成功");
}else {
System.out.println("遗憾,删除记录失败");
}
}
@Test
public void testUpdate() {
User user = new User();
user.setUsername("王aa");
user.setPassword("456123");
// user.setRegisterTime(new Timestamp(new Date().getTime()));
user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
user.setId(5);
UserDao dao = new UserDaoImpl();
int count = dao.update(user);
if (count > 0) {
System.out.println("恭喜,更新记录成功");
}else {
System.out.println("遗憾,更新记录失败");
}
}
@Test
public void testFindById() {
UserDao dao = new UserDaoImpl();
User user = dao.findById(1);
System.out.println(user);
}
@Test
public void testFindAll() {
UserDao dao = new UserDaoImpl();
List<User> users = dao.findAll();
for (User user:users) {
System.out.println(user);
}
}
@Test
public void testLogin() {
UserDao dao = new UserDaoImpl();
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 testLogin1() {
UserDao dao = new UserDaoImpl();
String username, password;
username = "howord";
password = "123456";
User user = dao.login(username, password);
if (user != null) {
System.out.println("恭喜,用户名与密码正确,登陆成功!");
}else {
System.out.println("遗憾,用户名与密码错误,登陆失败!");
}
}
@Test
public void testFindUsername() {
UserDao dao = new UserDaoImpl();
String username = "admin";
User user1 = dao.findUsername(username);
if (user1 != null) {
System.out.println("遗憾,用户名已存在,请重新输入用户名!");
}else {
System.out.println("恭喜,用户名不存在,可以注册!");
}
}
}
11、服务接口
服务接口调用数据访问接口,可以添加必要的业务逻辑。服务接口被控制层调用。
(1)学校服务接口CollegeService
package net.wlq.student.bean.service;
import net.wlq.student.bean.bean.College;
/**
* 功能:学校服务接口
*/
public interface CollegeService {
College findCollegeById(int id);
int updateCollege(College college);
}
(2)状态服务接口StatusService
package net.wlq.student.bean.service;
import net.wlq.student.bean.bean.Status;
/**
* 更能:状态服务接口
*/
public interface StatusService {
Status findStatusById(int id);
int updateStatus(Status status);
}
(3)学生服务接口StudentService
package net.wlq.student.bean.service;
import net.wlq.student.bean.bean.Student;
import java.util.List;
import java.util.Vector;
public interface StudentService {
int addStudent(Student student);
int deleteStudentById(String id);
int deleteStudentsByClass(String clazz);
int deleteStudentsByDepartment(String department);
int updateStudent(Student student);
Student findStudentById(String id);
List<Student> findStudentsByName(String name);
List<Student> findStudentsByClass(String clazz);
List<Student> findStudentsByDepartment(String department);
List<Student> findAllStudents();
Vector findRowsBySex();
Vector findRowsByClass();
Vector findRowsByDepartment();
}
(4)用户服务接口UserService
package net.wlq.student.bean.service;
import net.wlq.student.bean.bean.User;
import java.util.List;
public interface UserService {
int addUser(User user);
int deleteUserById(int id);
int updateUser(User user);
User findUserById(int id);
List<User> findAllUsers();
User login(String username,String password);
User findUsername(String username);
}
12、服务接口实现类
(1)学校服务接口实现类CollegeServiceImpl
package net.wlq.student.bean.service.impl;
import net.wlq.student.bean.bean.College;
import net.wlq.student.bean.dao.CollegeDao;
import net.wlq.student.bean.dao.impl.CollegeDaoImpl;
import net.wlq.student.bean.service.CollegeService;
/**
* 功能:学校服务接口实现类
*/
public class CollegeServiceImpl implements CollegeService {
/**
* 声明学校数据访问对象
*/
private CollegeDao collegeDao = new CollegeDaoImpl();
@Override
public College findCollegeById(int id) {
return collegeDao.findById(id);
}
@Override
public int updateCollege(College college) {
return collegeDao.update(college);
}
}
.test包里创建测试类TestCollegeServiceImpl:
编写测试方法testFindCollegeById()
编写测试方法testUpdateCollege():
(2)状态服务接口实现类StatusServiceImpl
package net.wlq.student.bean.service.impl;
import net.wlq.student.bean.bean.Status;
import net.wlq.student.bean.dao.StatusDao;
import net.wlq.student.bean.dao.impl.StatusDaoImpl;
import net.wlq.student.bean.service.StatusService;
/**
* 功能:状态服务接口实现类
*/
public class StatusServiceImpl implements StatusService {
/**
* 声明状态数据访问对象
*/
private StatusDao statusDao = new StatusDaoImpl();
@Override
public Status findStatusById(int id) {
return statusDao.findById(id);
}
@Override
public int updateStatus(Status status) {
return statusDao.update(status);
}
}
.test包里创建测试类TestStatusServiceImpl:
编写测试方法testFindStatusById():
编写测试方法testUpdateStatus():
3)学生服务接口实现类StudentServiceImpl
.test包里创建测试类TestStudentServiceImpl:
编写测试方法testFindStudentsByName():
package net.wlq.student.bean.service.impl;
import net.wlq.student.bean.bean.Student;
import net.wlq.student.bean.dao.StudentDao;
import net.wlq.student.bean.dao.impl.StudentDaoImpl;
import net.wlq.student.bean.service.StudentService;
import java.util.List;
import java.util.Vector;
/**
*功能:学生服务接口实现类
* 2019.6.21
*/
public class StudentServiceImpl implements StudentService {
/**
* 声明学生数据访问对象
*/
private StudentDao studentDao = new StudentDaoImpl();
@Override
public int addStudent(Student student) {
return studentDao.insert(student);
}
@Override
public int deleteStudentById(String id) {
return studentDao.deleteById(id);
}
@Override
public int deleteStudentsByClass(String clazz) {
return studentDao.deleteByClass(clazz);
}
@Override
public int deleteStudentsByDepartment(String department) {
return studentDao.deleteByDepartment(department);
}
@Override
public int updateStudent(Student student) {
return studentDao.update(student);
}
@Override
public Student findStudentById(String id) {
return studentDao.findById(id);
}
@Override
public List<Student> findStudentsByName(String name) {
return studentDao.findByName(name);
}
@Override
public List<Student> findStudentsByClass(String clazz) {
return studentDao.findByClass(clazz);
}
@Override
public List<Student> findStudentsByDepartment(String department) {
return studentDao.findByDepartment(department);
}
@Override
public List<Student> findAllStudents() {
return studentDao.findAll();
}
@Override
public Vector findRowsBySex() {
return studentDao.findRowsBySex();
}
@Override
public Vector findRowsByClass() {
return studentDao.findRowsByClass();
}
@Override
public Vector findRowsByDepartment() {
return studentDao.findRowsByDepartment();
}
}
(4)用户服务接口实现类UserServiceImpl
.test包里创建测试类TestUserServiceImpl:
编写测试方法testLogin()方法: