码迷,mamicode.com
首页 > 数据库 > 详细

封装JDBC操作数据库的方法

时间:2016-06-29 23:36:49      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:

自己动手封装java操作数据库的方法:

一:目录结构

技术分享

 

二:所需依赖的第三方jar包

这里只需引入mysql-connector-java-5.1.8-bin.jar,mysql数据库驱动jar包

 

三:代码

1:和数据库进行交互,首先是数据源,获取连接,代码如下:

 1 /**
 2  * 
 3  */
 4 package com.hlcui.datasource;
 5 
 6 import java.sql.Connection;
 7 import java.sql.DriverManager;
 8 import java.sql.SQLException;
 9 
10 /**
11  * @author Administrator 定义获取和关闭数据源的方法
12  */
13 public class DataSourceUtil {
14 
15     /**
16      * 注册数据库驱动
17      */
18     static {
19         try {
20             Class.forName("com.mysql.jdbc.Driver");
21         } catch (ClassNotFoundException e) {
22             e.printStackTrace();
23         }
24     }
25 
26     /**
27      * 获取数据源
28      * 
29      * @throws SQLException
30      */
31     public static Connection getConnection(String url, String user,
32             String password) throws SQLException {
33         return DriverManager.getConnection(url, user, password);
34     }
35 
36     /**
37      * 关闭数据源
38      * 
39      * @throws SQLException
40      */
41     public static void closeConnection(Connection conn) throws SQLException {
42         if (null != conn) {
43             conn.close();
44         }
45     }
46 }

 

2:有个数据库连接之后,可以对数据库进行操作了

  1 /**
  2  * 
  3  */
  4 package com.hlcui.dao;
  5 
  6 import java.sql.Connection;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 
 13 import com.hlcui.Constants;
 14 import com.hlcui.datasource.DataSourceUtil;
 15 import com.hlcui.entity.Student;
 16 
 17 /**
 18  * @author Administrator
 19  * 
 20  */
 21 public class DBUtil {
 22 
 23     /**
 24      * 查询所有学生信息
 25      * 
 26      * @return
 27      */
 28     public static List<Student> getAllStuInfo() {
 29         Connection conn = null;
 30         PreparedStatement ps = null;
 31         ResultSet rs = null;
 32         List<Student> stus = new ArrayList<Student>();
 33         try {
 34             conn = DataSourceUtil.getConnection(Constants.URL,
 35                     Constants.USERNAME, Constants.PASSWORD);
 36             String sql = "select * from student";
 37             ps = conn.prepareStatement(sql);
 38             rs = ps.executeQuery();
 39             while (rs.next()) {
 40                 int id = rs.getInt("id");
 41                 String name = rs.getString("name");
 42                 int age = rs.getInt("age");
 43                 double score = rs.getDouble("score");
 44                 Student s = new Student(id, name, age, score);
 45                 stus.add(s);
 46             }
 47 
 48         } catch (Exception e) {
 49             e.printStackTrace();
 50         } finally {
 51 
 52             try {
 53                 if (null != rs) {
 54                     rs.close();
 55                 }
 56                 if (null != ps) {
 57                     ps.close();
 58                 }
 59                 if (null != conn) {
 60                     DataSourceUtil.closeConnection(conn);
 61                 }
 62             } catch (SQLException e) {
 63                 e.printStackTrace();
 64             }
 65 
 66         }
 67         return stus;
 68     }
 69 
 70     /**
 71      * 根据id查询学生的信息
 72      */
 73     public static Student getStuInfoById(int id) {
 74         Connection conn = null;
 75         PreparedStatement ps = null;
 76         ResultSet rs = null;
 77         Student s = null;
 78         try {
 79             conn = DataSourceUtil.getConnection(Constants.URL,
 80                     Constants.USERNAME, Constants.PASSWORD);
 81             String sql = "SELECT * FROM student where id = ?";
 82             ps = conn.prepareStatement(sql);
 83             ps.setInt(1, id);
 84             rs = ps.executeQuery();
 85             while (rs.next()) {
 86                 String name = rs.getString("name");
 87                 int age = rs.getInt("age");
 88                 double score = rs.getDouble("score");
 89                 s = new Student(id, name, age, score);
 90             }
 91         } catch (Exception e) {
 92             e.printStackTrace();
 93         } finally {
 94             try {
 95                 if (null != rs) {
 96                     rs.close();
 97                 }
 98                 if (null != ps) {
 99                     ps.close();
100                 }
101                 if (null != conn) {
102                     DataSourceUtil.closeConnection(conn);
103                 }
104             } catch (Exception e2) {
105             }
106         }
107         return s;
108     }
109 
110     /**
111      * 增加学生信息
112      */
113     public static void saveStuInfo(Student stu) {
114         Connection conn = null;
115         PreparedStatement ps = null;
116         try {
117             conn = DataSourceUtil.getConnection(Constants.URL,
118                     Constants.USERNAME, Constants.PASSWORD);
119             String sql = "insert into student (id,name,age,score) values (?,?,?,?)";
120             ps = conn.prepareStatement(sql);
121             ps.setInt(1, stu.getId());
122             ps.setString(2, stu.getName());
123             ps.setInt(3, stu.getAge());
124             ps.setDouble(4, stu.getScore());
125             int insertCount = ps.executeUpdate();
126             System.out.println(isSuccess(insertCount));
127         } catch (Exception e) {
128             e.printStackTrace();
129         } finally {
130             try {
131                 if (null != ps) {
132                     ps.close();
133                 }
134                 if (null != conn) {
135                     conn.close();
136                 }
137             } catch (Exception e2) {
138                 e2.printStackTrace();
139             }
140         }
141     }
142 
143     /**
144      * 根据id删除学生信息
145      */
146     public static void deleteStuInfo(int id) {
147         Connection conn = null;
148         PreparedStatement ps = null;
149         try {
150             conn = DataSourceUtil.getConnection(Constants.URL,
151                     Constants.USERNAME, Constants.PASSWORD);
152             String sql = "delete from student where id = ?";
153             ps = conn.prepareStatement(sql);
154             ps.setInt(1, id);
155             int deleteCount = ps.executeUpdate();
156             System.out.println(isSuccess(deleteCount));
157         } catch (Exception e) {
158             e.printStackTrace();
159         } finally {
160             try {
161                 if (null != ps) {
162                     ps.close();
163                 }
164                 if (null != conn) {
165                     conn.close();
166                 }
167             } catch (Exception e2) {
168                 e2.printStackTrace();
169             }
170         }
171     }
172 
173     /**
174      * 根据id修改学生信息
175      */
176     public static void modifyStuInfo(Student stu) {
177         Connection conn = null;
178         PreparedStatement ps = null;
179         try {
180             conn = DataSourceUtil.getConnection(Constants.URL,
181                     Constants.USERNAME, Constants.PASSWORD);
182             String sql = "update student set name = ?,age = ? ,score = ? where id = ?";
183             ps = conn.prepareStatement(sql);
184             ps.setString(1, stu.getName());
185             ps.setInt(2, stu.getAge());
186             ps.setDouble(3, stu.getScore());
187             ps.setInt(4, stu.getId());
188             int count = ps.executeUpdate();
189             System.out.println(isSuccess(count));
190         } catch (Exception e) {
191             e.printStackTrace();
192         } finally {
193             try {
194                 if (null != ps) {
195                     ps.close();
196                 }
197                 if (null != conn) {
198                     conn.close();
199                 }
200             } catch (Exception e2) {
201                 e2.printStackTrace();
202             }
203         }
204     }
205 
206     /**
207      * 判断操作是否成功
208      */
209     public static String isSuccess(int count) {
210         if (count > 0) {
211             return "操作成功!";
212         } else {
213             return "操作失败!";
214         }
215     }
216 }

3:POJO实体类

 1 /**
 2  * 
 3  */
 4 package com.hlcui.entity;
 5 
 6 /**
 7  * @author Administrator
 8  * 
 9  */
10 public class Student {
11     private int id;
12     private String name;
13     private int age;
14     private double score;
15 
16     public Student() {
17 
18     }
19 
20     public Student(int id, String name, int age, double score) {
21         super();
22         this.id = id;
23         this.name = name;
24         this.age = age;
25         this.score = score;
26     }
27 
28     public int getId() {
29         return id;
30     }
31 
32     public void setId(int id) {
33         this.id = id;
34     }
35 
36     public String getName() {
37         return name;
38     }
39 
40     public void setName(String name) {
41         this.name = name;
42     }
43 
44     public int getAge() {
45         return age;
46     }
47 
48     public void setAge(int age) {
49         this.age = age;
50     }
51 
52     public double getScore() {
53         return score;
54     }
55 
56     public void setScore(double score) {
57         this.score = score;
58     }
59 
60 }

4:常量类Constants

 1 /**
 2  * 
 3  */
 4 package com.hlcui;
 5 
 6 /**
 7  * @author Administrator
 8  * 
 9  */
10 public class Constants {
11 
12     public static final String URL = "jdbc:mysql://localhost:3306/test";
13     public static final String USERNAME = "root";
14     public static final String PASSWORD = "root";
15 
16 }

 

四:测试类,验证是否能够操作数据库中数据

 1 /**
 2  * 
 3  */
 4 package com.hlcui.test;
 5 
 6 import java.sql.Connection;
 7 import java.sql.SQLException;
 8 import java.util.Iterator;
 9 import java.util.List;
10 
11 import org.junit.Test;
12 
13 import com.hlcui.Constants;
14 import com.hlcui.dao.DBUtil;
15 import com.hlcui.datasource.DataSourceUtil;
16 import com.hlcui.entity.Student;
17 
18 /**
19  * @author Administrator
20  * 
21  */
22 public class TestJdbc {
23 
24     /**
25      * 测试获取数据库连接
26      * 
27      * @throws SQLException
28      */
29     @Test
30     public void testGetConnection() throws SQLException {
31         Connection conn = DataSourceUtil.getConnection(Constants.URL,
32                 Constants.USERNAME, Constants.PASSWORD);
33         System.out.println("conn:" + conn);
34 
35     }
36 
37     /**
38      * 测试获取所有的学生信息
39      */
40     @Test
41     public void testGetAllStuInfo() {
42         List<Student> stus = DBUtil.getAllStuInfo();
43         Iterator<Student> it = stus.iterator();
44         while (it.hasNext()) {
45             Student s = it.next();
46             System.out.println(s.getId() + "," + s.getName() + "," + s.getAge()
47                     + "," + s.getScore());
48         }
49     }
50 
51     /**
52      * 测试根据id获取学生信息
53      */
54     @Test
55     public void testGetStuInfoById() {
56         int id = 1;
57         Student s = DBUtil.getStuInfoById(id);
58         System.out.println(s.getId() + "," + s.getName() + "," + s.getAge()
59                 + "," + s.getScore());
60     }
61 
62     /**
63      * 测试添加学生信息
64      */
65     @Test
66     public void testSaveStuInfo() {
67         Student s = new Student(4, "Lucy", 27, 100.0);
68         DBUtil.saveStuInfo(s);
69     }
70 
71     /**
72      * 测试删除学生信息
73      */
74     @Test
75     public void testDeleteStuInfo() {
76         int id = 4;
77         DBUtil.deleteStuInfo(id);
78     }
79     
80     /**
81      * 测试修改学生信息
82      */
83     @Test
84     public void testModifyStuInfo(){
85         Student s = new Student(3,"Lili",24,9000.0);
86         DBUtil.modifyStuInfo(s);
87     }
88 
89 }

以上代码均已验证正确。

封装JDBC操作数据库的方法

标签:

原文地址:http://www.cnblogs.com/warrior4236/p/5628386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!