为了帮助大家熟练应用JDBC编程,接下来,在本节将通过一个综合案例来讲解JDBC的基本操作,确保大家能够深刻理解JDBC的增、删、改、查,灵活利用JDBC完成对数据库的各项操作。
1. 创建一个Java类Student
在工程chapter01下创建com.qfedu.jdbc.domain包,并在该包下创建用于保存学生数据的类Student,具体代码如例1-1所示。
【例1-1】 Student.java
1 package com.qfedu.jdbc.domain;
2 public class Student {
3 private int id;
4 private String sname;
5 private String age;
6 private String course;
7 public Student() {
8 super();
9 }
10 public Student(int id, String sname, String age, String course) {
11 super();
12 this.id = id;
13 this.sname = sname;
14 this.age = age;
15 this.course = course;
16 }
17 public int getId() {
18 return id;
19 }
20 public void setId(int id) {
21 this.id = id;
22 }
23 public String getSname() {
24 return sname;
25 }
26 public void setSname(String sname) {
27 this.sname = sname;
28 }
29 public String getAge() {
30 return age;
31 }
32 public void setAge(String age) {
33 this.age = age;
34 }
35 public String getCourse() {
36 return course;
37 }
38 public void setCourse(String course) {
39 this.course = course;
40 }
41 @Override
42 public String toString() {
43 return "Student [id=" + id + ", sname=" + sname + ", age=" + age +
44 ", course=" + course + "]";
45 }
46 }
2. 创建JDBCUtils工具类
在开发过程中,每次对数据库的操作都需要注册驱动、获取连接、关闭资源等,造成大量重复代码。为了降低冗余,提升开发效率,一般将JDBC的相关操作封装到JDBC工具类中。在src目录下新建com.qfedu.jdbc.utils包,并在该包下创建JDBCUtils工具类,具体代码如例1-2所示。
【例1-2】 JDBCUtils.java
1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 public class JDBCUtils {
7 private static String url = "jdbc:mysql://localhost:3306/chapter01";
8 private static String user = "root";
9 private static String pass = "root";
10 private static Connection conn = null;
11 static{
12 try{
13 Class.forName("com.mysql.jdbc.Driver");
14 conn = DriverManager.getConnection(url, user, pass);
15 }catch(Exception ex){
16 ex.printStackTrace();
17 //数据库连接失败,直接停止程序,抛出运行时期异常
18 throw new RuntimeException("数据库连接失败");
19 }
20 }
21 //获取链接
22 public static Connection getConnecton(){
23 return conn;
24 }
25 //释放资源
26 public static void release(Connection conn,PreparedStatement
27 pstat,ResultSet rs) {
28 if (rs!=null) {
29 try {
30 rs.close();
31 } catch (SQLException e) {
32 e.printStackTrace();
33 }
34 rs=null;
35 }
36 release(conn,pstat);
37 }
38 public static void release(Connection conn,PreparedStatement pstat) {
39 if (pstat!=null) {
40 try {
41 pstat.close();
42 } catch (SQLException e) {
43 e.printStackTrace();
44 }
45 pstat=null;
46 }
47 if (conn !=null) {
48 try {
49 conn.close();
50 } catch (SQLException e) {
51 e.printStackTrace();
52 }
53 conn=null;
54 }
55 }
56 }
3. 新建StudentDao类
在src目录下新建com.qfedu.jdbc.dao包,并在该包下新建StudentDao类,该类提供对数据库表的增加、修改、删除、查询等操作,具体代码如例1-3所示。
【例1-3】 StudentDao.java
1 package com.qfedu.jdbc.dao;
2 import java.sql.Connection;
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.util.ArrayList;
7 import com.qfedu.jdbc.domain.Student;
8 import com.qfedu.jdbc.utils.JDBCUtils;
9 public class StudentDao {
10 //添加Student
11 public boolean insert(Student student){
12 boolean flag =false ;
13 PreparedStatement pstat = null;
14 Connection conn = JDBCUtils.getConnecton();
15 String sql ="insert into student(sid,sname,age,course)
16 values(?,?,?,?)";
17 try {
18 pstat = conn.prepareStatement(sql);
19 pstat.setInt(1, student.getSid());
20 pstat.setString(2, student.getSname());
21 pstat.setString(3, student.getAge());
22 pstat.setString(4, student.getCourse());
23 int num = pstat.executeUpdate();
24 if (num>0) {
25 flag =true;
26 }
27 } catch (SQLException e) {
28 e.printStackTrace();
29 }finally {
30 JDBCUtils.release(conn, pstat);
31 }
32 return flag;
33 }
34 //更新Student
35 public boolean update(Student student){
36 boolean flag =false ;
37 PreparedStatement pstat = null;
38 Connection conn = JDBCUtils.getConnecton();
39 String sql ="update student set sname=?,age=?,course=? where
40 sid=? ";
41 try {
42 pstat = conn.prepareStatement(sql);
43 pstat.setInt(4, student.getSid());
44 pstat.setString(1, student.getSname());
45 pstat.setString(2, student.getAge());
46 pstat.setString(3, student.getCourse());
47 int num = pstat.executeUpdate();
48 if (num>0) {
49 flag =true;
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 }finally {
54 JDBCUtils.release(conn, pstat);
55 }
56 return flag;
57 }
58 //删除Student
59 public boolean delete(Student student){
60 boolean flag =false ;
61 PreparedStatement pstat = null;
62 Connection conn = JDBCUtils.getConnecton();
63 String sql ="delete from student where sid=?";
64 try {
65 pstat = conn.prepareStatement(sql);
66 pstat.setInt(1, student.getSid());
67 int num = pstat.executeUpdate();
68 if (num>0) {
69 flag =true;
70 }
71 } catch (SQLException e) {
72 e.printStackTrace();
73 }finally {
74 JDBCUtils.release(conn, pstat);
75 }
76 return flag;
77 }
78 //查询所有Student
79 public ArrayListselectAll(){
80 PreparedStatement pstat = null;
81 Connection conn = JDBCUtils.getConnecton();
82 String sql ="select * from student";
83 ArrayListlist = new ArrayList<>();
84 try {
85 pstat = conn.prepareStatement(sql);
86 ResultSet rs = pstat.executeQuery(sql);
87 while (rs.next()) {
88 Student newStudent = new Student();
89 newStudent.setSid(rs.getInt("sid"));
90 newStudent.setSname( rs.getString("sname"));
91 newStudent.setAge(rs.getString("age"));
92 newStudent.setCourse(rs.getString("course"));
93 list.add(newStudent);
94 }
95 } catch (SQLException e) {
96 e.printStackTrace();
97 }finally {
98 JDBCUtils.release(conn, pstat);
99 }
100 return list;
101 }
102 //查询单个Student
103 public Student selectOne(Student student){
104 PreparedStatement pstat = null;
105 Connection conn = JDBCUtils.getConnecton();
106 String sql ="select * from student where sid = ? ";
107 Student newStudent = new Student();
108 try {
109 pstat = conn.prepareStatement(sql);
110 pstat.setInt(1, student.getSid());
111 ResultSet rs = pstat.executeQuery();
112 while (rs.next()) {
113 newStudent.setSid(rs.getInt("sid"));
114 newStudent.setSname( rs.getString("sname"));
115 newStudent.setAge(rs.getString("age"));
116 newStudent.setCourse(rs.getString("course"));
117 }
118 } catch (SQLException e) {
119 e.printStackTrace();
120 }finally {
121 JDBCUtils.release(conn, pstat);
122 }
123 return newStudent;
124 }
125 }
4. 编写测试类TestInsert
在src目录下新建com.qfedu.jdbc.test包,并在该包下新建TestInsert类,该类用于测试向表中添加数据的操作,具体代码如例1-4所示。
【例1-4】 TestInsert.java
1 package com.qfedu.jdbc.test;
2 import com.qfedu.jdbc.dao.StudentDao;
3 import com.qfedu.jdbc.domain.Student;
4 public class TestInsert {
5 public static void main(String[] args) {
6 StudentDao studentDao = new StudentDao();
7 Student student = new Student();
8 student.setSid(10);
9 student.setSname("sunqi");
10 student.setAge("23");
11 student.setCourse("python");
12 studentDao.insert(student);
13 }
14 }
执行TestInsert类,向数据表student中插入数据,通过SQL语句测试数据是否添加成功,执行结果如下所示。
mysql> SELECT * FROM STUDENT;
+-----+-------------+------+--------+
| sid | sname | age | course |
+-----+-------------+------+--------+
| 1 | zhangsan | 20 | Java |
| 2 | lisi | 21 | Java |
| 3 | wangwu | 22 | Java |
| 4 | zhaoliu | 22 | Python |
| 5 | sunqi | 22 | PHP |
| 6 | zhangsansan | 22 | PHP |
| 7 | name0 | 22 | Java |
| 8 | name1 | 22 | Java |
| 9 | name2 | 22 | Java |
| 10 | sunqi | 23 | Python |
+-----+-------------+------+--------+
10 rows in set (0.00 sec)
从以上执行结果可以看出,程序成功向数据表添加一条数据。
5. 编写测试类TestUpdate
在src目录下的com.qfedu.jdbc.test包下新建TestUpdate类,该类用于测试更新表中数据的操作,具体代码如例1-5所示。
【例1-5】 TestUpdate.java
1 package com.qfedu.jdbc.test;
2 import com.qfedu.jdbc.dao.StudentDao;
3 import com.qfedu.jdbc.domain.Student;
4 public class TestUpdate {
5 public static void main(String[] args) {
6 StudentDao studentDao = new StudentDao();
7 Student student = new Student();
8 student.setSid(10);
9 student.setSname("zhouba");
10 student.setAge("24");
11 student.setCourse("Java");
12 studentDao.update(student);
13 }
14 }
执行TestUpdate类,更新数据库中sid值为10的数据信息,通过SQL语句测试数据是否更新成功,执行结果如下所示。
mysql> SELECT * FROM STUDENT;
+-----+-------------+------+--------+
| sid | sname | age | course |
+-----+-------------+------+--------+
| 1 | zhangsan | 20 | Java |
| 2 | lisi | 21 | Java |
| 3 | wangwu | 22 | Java |
| 4 | zhaoliu | 22 | Python |
| 5 | sunqi | 22 | PHP |
| 6 | zhangsansan | 22 | PHP |
| 7 | name0 | 22 | Java |
| 8 | name1 | 22 | Java |
| 9 | name2 | 22 | Java |
| 10 | zhouba | 24 | Java |
+-----+-------------+------+--------+
10 rows in set (0.00 sec)
从以上执行结果可以看出,程序成功更新sid值为10的数据。
6. 编写测试类TestDelete
在src目录下的com.qfedu.jdbc.test包下新建TestDelete类,该类用于测试删除表中数据的操作,具体代码如例1-6所示。
【例1-6】 TestDelete.java
1 package com.qfedu.jdbc.test;
2 import com.qfedu.jdbc.dao.StudentDao;
3 import com.qfedu.jdbc.domain.Student;
4 public class TestDelete {
5 public static void main(String[] args) {
6 StudentDao studentDao = new StudentDao();
7 Student student = new Student();
8 student.setSid(10);
9 studentDao.delete(student);
10 }
11 }
执行TestDelete类,删除数据库中sid值为10的数据信息,通过SQL语句测试数据是否删除成功,执行结果如下所示。
mysql> SELECT * FROM STUDENT;
+-----+-------------+------+--------+
| sid | sname | age | course |
+-----+-------------+------+--------+
| 1 | zhangsan | 20 | Java |
| 2 | lisi | 21 | Java |
| 3 | wangwu | 22 | Java |
| 4 | zhaoliu | 22 | Python |
| 5 | sunqi | 22 | PHP |
| 6 | zhangsansan | 22 | PHP |
| 7 | name0 | 22 | Java |
| 8 | name1 | 22 | Java |
| 9 | name2 | 22 | Java |
+-----+-------------+------+--------+
9 rows in set (0.00 sec)
从以上执行结果可以看出,程序成功删除sid值为10的数据。
7. 编写测试类TestSelectOne
在src目录下的com.qfedu.jdbc.test包下新建TestSelectOne类,该类用于测试查询表中单条数据的操作,具体代码如例1-7所示。
【例1-7】 TestSelectOne.java
1 package com.qfedu.jdbc.test;
2 import com.qfedu.jdbc.dao.StudentDao;
3 import com.qfedu.jdbc.domain.Student;
4 public class TestSelectOne {
5 public static void main(String[] args) {
6 StudentDao studentDao = new StudentDao();
7 Student student = new Student();
8 student.setSid(1);
9 Student findStudent = studentDao.selectOne(student);
10 System.out.println(findStudent.toString());
11 }
12 }
执行TestSelectOne类,程序的运行结果如图1.1所示。
图1.1 运行结果
从以上执行结果可以看出,程序成功查询出sid值为1的数据并输出到控制台。
8. 编写测试类TestSelectAll
在src目录下的com.qfedu.jdbc.test包下新建TestSelectAll类,该类用于测试查询表中所有数据的操作,具体代码如例1-8所示。
【例1-8】 TestSelectAll.java
1 package com.qfedu.jdbc.test;
2 import java.util.ArrayList;
3 import com.qfedu.jdbc.dao.StudentDao;
4 import com.qfedu.jdbc.domain.Student;
5 public class TestSelectAll {
6 public static void main(String[] args) {
7 StudentDao studentDao = new StudentDao();
8 ArrayListlist = studentDao.selectAll();
9 for (Student student : list) {
10 System.out.println(student.toString());
11 }
12 }
13 }
执行TestSelectAll类,程序的运行结果如图1.2所示。
图1.2 运行结果
从以上执行结果可以看出,程序成功查询出表student中所有数据并输出到控制台。