hooyantsing's Blog

DBHelper

字数统计: 1.9k阅读时长: 11 min
2019/12/05

DBHelper.java    v1.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package tandard.util.dbhelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import  org.apache.commons.beanutils.BeanUtils;
public class DBHelper {
    
    /*
     * 通过连接池方式获取数据库连接
     */
    public static Connection getConnection()  {
       try {
           //创建JNDI上下文对象
           Context ctx = new  InitialContext();
           DataSource ds = (DataSource)  ctx.lookup("java:comp/env/mysql/<数据库名>");
           return ds.getConnection();
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
    }
    
    /*
     * 更新数据库中的数据
     */
    public static int update(String sql,  Object... param) {
       Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <=  param.length; i++) {
               ps.setObject(i, param[i -  1]);
           }
           return ps.executeUpdate();
       } catch (SQLException e) {
           throw new RuntimeException("更新数据失败", e);
       } finally {
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
    
    /*
     * 查询所需要的数据 返回对象打包成List
     */
    public static List<Map<String, Object>>  selectList(String sql, Object... param) {
       Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <=  param.length; i++) {
               ps.setObject(i, param[i -  1]);
           }
           ResultSet rs = ps.executeQuery();
           List<Map<String, Object>> ret =  new ArrayList<Map<String, Object>>();
           ResultSetMetaData rsmd =  rs.getMetaData();
           while (rs.next()) {
               Map<String, Object> row = new  LinkedHashMap<String, Object>();
               for (int i = 1; i <  rsmd.getColumnCount() + 1; i++) {
                  String ColumnName =  rsmd.getColumnName(i);
                  row.put(ColumnName,  rs.getObject(ColumnName));
               }
               ret.add(row);
           }
           return ret;
       } catch (SQLException e) {
           throw new RuntimeException("查询数据失败", e);
       } finally {
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
    
    /*
     * 快速查询 返回对象Object
     */
    public static Object selectValue(String  sql, Object... param) {
        Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <=  param.length; i++) {
               ps.setObject(i, param[i -  1]);
           }
           ResultSet rs = ps.executeQuery();
           if (rs.next()) {
               return rs.getObject(1);
           } else {
               return null;
           }
       } catch (SQLException e) {
           throw new RuntimeException("查询数据失败", e);
       } finally {
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }   
    }
    
    /*
     * 分页:通用实体类
     */
    public static class Page {
        private List<Map<String,Object>>  data;
        private long total;
       private int page;
       private int rows;
        public Page(long total, int page,  int rows, List<Map<String,Object>> data) {
            this.data = data;
            this.page = page;
            this.rows = rows;
            this.total = total;
        }
        public List<Map<String,Object>>  getData() {
            return data;
        }
        public long getTotal() {
            return total;
        }
        public int getPage(){
            return page;
        }
        public int getFirstPage(){
            return 1;
        }
        public int getPreviousPage(){
            return page > 1 ? page - 1 : 1;
        }
        public int getNextPage(){
            int lastpage = getLastPage();
            return page < lastpage ? page + 1  : lastpage;
        }
        public int getLastPage(){
            long lastPage = total / rows;
            return (int) (total % rows == 0 ?   lastPage : (lastPage + 1));
        }
    }
    
    /*
     * 分页:Oracle
     */
    public static Page  selectPageForOracle(String sql, int page,  int rows, Object... params) {
        String totalSql = "select count(*)  from ("+sql+")";   
        Object totalObj =  selectValue(totalSql, params);
        long total =  Long.parseLong(totalObj.toString());
        int startRow = (page - 1 ) * rows;
        int endRow= page * rows + 1;
        String pageSql = " select * from "
               + "(select a.*,rownum rn from  ("+sql+") a where rownum < "+endRow+") a"
               + " where a.rn > " +  startRow;
        List<Map<String,Object>> data =  selectList(pageSql,params);
        return new Page(total, page, rows,  data);
    }
    
    /*
     * 分页:MySQL
     */
    public static Page  selectPageForMysql(String sql, int page, int  rows, Object... params) {
        String totalSql = "select count(*)  from ("+sql+") a";   
        Object totalObj =  selectValue(totalSql, params);
        long total =  Long.parseLong(totalObj.toString());
        int startRow = (page - 1 ) * rows;
        String pageSql = "select * from  ("+sql+") a limit " + startRow + ", " +  rows;
        List<Map<String,Object>> data =  selectList(pageSql,params);
        return new Page(total, page, rows,  data);
    }
    
    /*
     * 将List<Map<String,Object>> 转换 实体类
     */
    public static <T> List<T>  populate(List<Map<String, Object>> list,  Class<T> cls) {
       List<T> retList = new  ArrayList<T>();
       for(Map<String, Object> row : list)  {
           try {
               T p = cls.newInstance();
               BeanUtils.populate(p, row);
               retList.add(p);
           } catch (Exception e) {
               throw new  RuntimeException(e);
           }
           
       }
       return retList;
    }
}

DBHelper.java    v1.0.1

更新内容:

完善了getConnection方法,如果连接池失效,将通过常规方式获取数据库连接,提升了程序的健壮性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package com.yc.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import  org.apache.commons.beanutils.BeanUtils;
public class DBHelper {
    /*
     * 与数据库建立连接
     */
    public static Connection getConnection()  {
       Connection conn = null;
       try {
           Context ctx = new  InitialContext();
           DataSource ds = (DataSource)  ctx.lookup("java:comp/env/mysql/hooyantsing666");
           conn = ds.getConnection();
       } catch (Exception e) {
           try {
               Class.forName("com.mysql.jdbc.Driver");
               String url =   "jdbc:mysql://127.0.0.1/yishuwang";
               String user = "root";
               String password = "a";
               conn =  DriverManager.getConnection(url,user,password);
           } catch (Exception e1) {
               e1.printStackTrace();
           }
       }
       if(conn==null) {
           throw new RuntimeException();
       }
       return conn;
    }
    
    /*
     * 更新数据库中的数据
     */
    public static int update(String sql,  Object... param) {
       Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <=  param.length; i++) {
               ps.setObject(i, param[i -  1]);
           }
           return ps.executeUpdate();
       } catch (SQLException e) {
           throw new RuntimeException("更新数据失败", e);
       } finally {
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
    
    /*
     * 查询所需要的数据 返回对象打包成List
     */
    public static List<Map<String, Object>>  selectList(String sql, Object... param) {
       Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <=  param.length; i++) {
               System.out.println(param[i-1]);
               ps.setObject(i, param[i -  1]);
           }
           ResultSet rs = ps.executeQuery();
           List<Map<String, Object>> ret =  new ArrayList<Map<String, Object>>();
           ResultSetMetaData rsmd =  rs.getMetaData();
           while (rs.next()) {
               Map<String, Object> row = new  LinkedHashMap<String, Object>();
               for (int i = 1; i <  rsmd.getColumnCount() + 1; i++) {
                  String ColumnName =  rsmd.getColumnName(i);
                  row.put(ColumnName,  rs.getObject(ColumnName));
               }
               ret.add(row);
           }
           return ret;
       } catch (SQLException e) {
           throw new RuntimeException("查询数据失败", e);
       } finally {
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
    
    /*
     * 快速查询 返回对象Object
     */
    public static Object selectValue(String  sql, Object... param) {
        Connection conn = null;
       try {
           conn = getConnection();
           PreparedStatement ps =  conn.prepareStatement(sql);
           System.out.println(sql);
           for (int i = 1; i <= param.length; i++) {
               ps.setObject(i, param[i -  1]);
           }
           ResultSet rs = ps.executeQuery();
           if (rs.next()) {
               return rs.getObject(1);
           } else {
               return null;
           }
       } catch (SQLException e) {
           throw new RuntimeException("查询数据失败", e);
       } finally {
           try {
               if(conn!=null) {
                  conn.close();
               }
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }   
    }
    
    /*
     * 分页:通用实体类
     */
    public static class Page {
        private List<Map<String,Object>>  data;
        private long total;
       private int page;
       private int rows;
        public Page(long total, int page,  int rows, List<Map<String,Object>> data) {
            this.data = data;
            this.page = page;
            this.rows = rows;
            this.total = total;
        }
        public List<Map<String,Object>>  getData() {
            return data;
        }
        public long getTotal() {
            return total;
        }
        public int getPage(){
            return page;
        }
        //首页
        public int getFirstPage(){
            return 1;
        }
        //上一页
        public int getPreviousPage(){
            return page > 1 ? page - 1 : 1;
        }
        //下一页
        public int getNextPage(){
            int lastpage = getLastPage();
            return page < lastpage ? page + 1  : lastpage;
        }
        //尾页
        public int getLastPage(){
            long lastPage = total / rows;
            return (int) (total % rows == 0 ?   lastPage : (lastPage + 1));
        }
    }
    
    /*
     * 分页:Oracle
     */
    public static Page  selectPageForOracle(String sql, int page,  int rows, Object... params) {
        String totalSql = "select count(*)  from ("+sql+")";   
        Object totalObj =  selectValue(totalSql, params);
        long total =  Long.parseLong(totalObj.toString());
        int startRow = (page - 1 ) * rows;
        int endRow= page * rows + 1;
        String pageSql = " select * from "
               + "(select a.*,rownum rn from  ("+sql+") a where rownum < "+endRow+") a"
               + " where a.rn > " +  startRow;
        List<Map<String,Object>> data =  selectList(pageSql,params);
        return new Page(total, page, rows,  data);
    }
    
    /*
     * 分页:MySQL
     */
    public static Page  selectPageForMysql(String sql, int page, int  rows, Object... params) {
        String totalSql = "select count(*)  from ("+sql+") a";   
        Object totalObj =  selectValue(totalSql, params);
        long total =  Long.parseLong(totalObj.toString());
        int startRow = (page - 1 ) * rows;
        String pageSql = "select * from  ("+sql+") a limit " + startRow + ", " +  rows;
        List<Map<String,Object>> data =  selectList(pageSql,params);
        return new Page(total, page, rows,  data);
    }
    
    /*
     * 将List<Map<String,Object>> 转换  实体类
     */
    public static <T> List<T>  populate(List<Map<String, Object>> list,  Class<T> cls) {
       List<T> retList = new  ArrayList<T>();
       for(Map<String, Object> row : list)  {
           try {
               T p = cls.newInstance();
               BeanUtils.populate(p, row);
               retList.add(p);
           } catch (Exception e) {
               throw new  RuntimeException(e);
           }
           
       }
       return retList;
    }
}
CATALOG