MySQL实现JDBC-简单案例演示
目录
JDBC案例student学生表的CRUD
CRUD操作就是增删查改操作。
数据准备
(1)创建SQL表
在SQLyog的上面创建数据库db14,数据表student,然后添加数据。
-- 创建db14数据库
CREATE DATABASE db14;
-- 使用db14数据库
USE db14;
-- 创建student表
CREATE TABLE student(
sid INT PRIMARY KEY AUTO_INCREMENT, -- 学生id
NAME VARCHAR(20), -- 学生姓名
age INT, -- 学生年龄
birthday DATE -- 学生生日
);
-- 添加数据
INSERT INTO student VALUES (NULL,'张三',23,'1999-09-23'),
(NULL,'李四',24,'1998-08-10'),
(NULL,'王五',25,'1996-06-06'),
(NULL,'赵六',26,'1994-10-20');
(2)创建Student类
上述SQL表中,有四个字段,Student类的成员变量的数据类型、变量名要与之对应!!!
自定义类的功能是为了封装表中的每一列数据,成员变量和列保持一致。所有的基本数据类型都必须使用其对应的包装类,以避免表中的null值无法赋值。(因为null不能赋值给基本数据类型)
import java.util.Date;
public class Student {
private Integer sid;
private String name;
private Integer age;
private Date birthday;
// 构造方法
public Student() {
}
public Student(Integer sid, String name, Integer age, Date birthday) {
this.sid = sid;
this.name = name;
this.age = age;
this.birthday = birthday;
}
// 创建getter 和 setter方法
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
// toString方法
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
详细过程
实现我们要先提一下一个概念:
Java中的分成思想。
DAO、Service、Controller层
DAO(Data Access Object)
直接看英文意思就是“数据访问对象”,也就是做一个“接口”
而DAO层主要是做数据持久层的工作,负责与数据库进行联络的一些任务都封装在此,DAO层的设计首先是设计DAO的接口,然后在Spring的配置文件中定义此接口的实现类,然后就可在模块中调用此接口来进行数据业务的处理,而不用关心此接口的具体实现类是哪个类,显得结构非常清晰,DAO层的数据源配置,以及有关数据库连接的参数都在Spring的配置文件中进行配置。
Service(中间层、业务逻辑层—做个接口)
Service层主要编写具体业务逻辑,每个Service一般包含一组相关的业务逻辑(比如“用户管理”是一个Service,”文章管理“是一个Service)
Service层主要负责业务模块的逻辑应用设计。同样是首先设计接口,再设计其实现的类,接着在Spring的配置文件中配置其实现的关联。这样我们就可以在应用中调用Service接口来进行业务处理。Service层的业务实现,具体要调用到已定义的DAO层的接口,封装Service层的业务逻辑有利于通用的业务逻辑的独立性和重复利用性,程序显得非常简洁。
Controaller(控制层)
其实相当于Servlet那一层所做的事
Controller层负责具体的业务模块流程的控制,在此层里面要调用Serice层的接口来控制业务流程,控制的配置也同样是在Spring的配置文件里面进行,针对具体的业务流程,会有不同的控制器,我们具体的设计过程中可以将流程进行抽象归纳,设计出可以重复利用的子单元流程模块,这样不仅使程序结构变得清晰,也大大减少了代码量。
该内容出自:JavaWeb开发中的分层思想(一) - 余月七 - 博客园 (cnblogs.com)https://www.cnblogs.com/yuyueq/p/14546053.html
在我们的这个项目中:
domain中的Student是实体类,controller、service、dao分别对应上述的3个层。
domain包下的Student类:
package JDBC.domain;
import java.util.Date;
public class Student {
private Integer sid;
private String name;
private Integer age;
private Date birthday;
// 构造方法
public Student() {
}
public Student(Integer sid, String name, Integer age, Date birthday) {
this.sid = sid;
this.name = name;
this.age = age;
this.birthday = birthday;
}
// 创建getter 和 setter方法
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
// toString方法
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
dao包下的StudentDao接口:
package JDBC.dao;
import JDBC.domain.Student;
import java.util.ArrayList;
public interface StudentDao {
//查询所有学生
public abstract ArrayList<Student> findAll();
//条件查询,根据id获取学生信息
public abstract Student findById(Integer id);
//新增学生信息
public abstract int insert(Student stu);
//修改学生信息
public abstract int update(Student stu);
//删除学生信息
public abstract int delete(Integer id);
}
dao包下的StudentDaoImpl实现类:
package JDBC.dao;
import JDBC.domain.Student;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.SimpleFormatter;
public class StudentDaoImpl implements StudentDao {
@Override
public ArrayList<Student> findAll() {
ArrayList<Student> list = new ArrayList<>();
Connection con = null;
Statement stat = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db14";
con = DriverManager.getConnection(url, "root", "888888");
stat = con.createStatement();
String sql = "SELECT * FROM student";
rs = stat.executeQuery(sql);
while (rs.next()) {
Integer sid = rs.getInt("sid");
String name = rs.getString("name");
Integer age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
Student stu = new Student(sid,name,age,birthday);
list.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return list;
}
@Override
public Student findById(Integer id) {
Student stu = new Student();
Connection con = null;
Statement stat = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db14";
con = DriverManager.getConnection(url, "root", "888888");
stat = con.createStatement();
String sql = "SELECT * FROM student WHERE sid='"+id+"'";
rs = stat.executeQuery(sql);
while (rs.next()) {
Integer sid = rs.getInt("sid");
String name = rs.getString("name");
Integer age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
stu.setSid(sid);
stu.setName(name);
stu.setAge(age);
stu.setBirthday(birthday);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return stu;
}
@Override
public int insert(Student stu) {
Connection con = null;
Statement stat = null;
int result = 0;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db14";
con = DriverManager.getConnection(url, "root", "888888");
stat = con.createStatement();
Date d = stu.getBirthday();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(d);
String sql = "INSERT INTO student VALUES ('"+stu.getSid()+"','"+stu.getName()+"','"+stu.getAge()+"','"+birthday+"')";
result = stat.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return result;
}
@Override
public int update(Student stu) {
Connection con = null;
Statement stat = null;
int result = 0;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db14";
con = DriverManager.getConnection(url, "root", "888888");
stat = con.createStatement();
Date d = stu.getBirthday();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthday = sdf.format(d);
String sql = "UPDATE student SET sid='"+stu.getSid()+"',name='"+stu.getName()+"',age='"+stu.getAge()+"',birthday='"+birthday+"' WHERE sid='"+stu.getSid()+"'";
result = stat.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return result;
}
@Override
public int delete(Integer id) {
Connection con = null;
Statement stat = null;
int result = 0;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db14";
con = DriverManager.getConnection(url, "root", "888888");
stat = con.createStatement();
String sql = "DELETE FROM student WHERE sid='"+id+"'";
result = stat.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return result;
}
}
service包下的StudentService接口:
package JDBC.service;
import JDBC.domain.Student;
import java.sql.SQLException;
import java.util.ArrayList;
public interface StudentService {
//查询所有学生
public abstract ArrayList<Student> findAll() throws SQLException;
//条件查询,根据id获取学生信息
public abstract Student findById(Integer id);
//新增学生信息
public abstract int insert(Student stu);
//修改学生信息
public abstract int update(Student stu);
//删除学生信息
public abstract int delete(Integer id);
}
service包下的StudentServiceImpl实现类:
package JDBC.service;
import JDBC.dao.StudentDao;
import JDBC.dao.StudentDaoImpl;
import JDBC.domain.Student;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
public class StudentServiceImpl implements StudentService{
// 先声明!
private StudentDao dao = new StudentDaoImpl();
@Override
public ArrayList<Student> findAll() {
return dao.findAll();
}
@Override
public Student findById(Integer id) {
return dao.findById(id);
}
@Override
public int insert(Student stu) {
return dao.insert(stu);
}
@Override
public int update(Student stu) {
return dao.update(stu);
}
@Override
public int delete(Integer id) {
return dao.delete(id);
}
}
controller包下的Studentcontroller类:
package JDBC.controller;
import JDBC.domain.Student;
import JDBC.service.StudentService;
import JDBC.service.StudentServiceImpl;
import org.junit.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class StudentController {
//声明一个service对象
private StudentService service = new StudentServiceImpl();
/*
查询所有学生信息
*/
@Test
public void findAll() throws SQLException {
ArrayList<Student> list = service.findAll();
for (Student stu : list) {
System.out.println(stu);
}
}
/*
条件查询,根据id查询学生信息
*/
@Test
public void findById() {
Student stu = service.findById(3);
System.out.println(stu);
}
/*
添加学生信息
*/
@Test
public void insert() {
Student stu = new Student(5,"周七",19,new Date());
int result = service.insert(stu);
if(result != 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
}
/*
修改学生信息
*/
@Test
public void update() {
Student stu = service.findById(5);
stu.setName("周奇奇");
int result = service.update(stu);
if (result != 0) {
System.out.println("修改成功!");
} else {
System.out.println("修改失败!");
}
}
/*
删除学生信息
*/
@Test
public void delete() {
int result = service.delete(5);
if(result != 0) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
}
}