JDBCUtil数据库查询工具类的终极封装

本文详细介绍了JDBC工具类的实现,包括数据库连接的获取、SQL执行、对象映射及资源关闭等核心功能,适用于Java应用程序中对数据库的高效操作。

https://blog.youkuaiyun.com/qxqx451/article/details/79422029

JDBCUtil.class

package com.hwadee.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.hwadee.entity.Book;
import com.hwadee.entity.User;

public class JDBCUtil {
    public static String url = null;
    public static String username = null;
    public static String password = null;
    public static String Driver = null;
    static {
        InputStream inputStream = JDBCUtil.class.getResourceAsStream("/db.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Driver = properties.getProperty("Driver");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //加载数据库驱动
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
/**
 * 获取数据库连接对象
 * @return
 */
    public static Connection getConnection() {
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

/**
 * 添加删除修改数据
 * @return
 */
    public static boolean insertDeleteUpdateExecute(String sql,ArrayList<Object> paras) {
        Connection conn=getConnection();
        PreparedStatement pst=null;
        boolean flag = false;
        int index = 1;
        try {
            pst=conn.prepareStatement(sql);
            if(paras != null&& paras.size()>0) {
                pst.clearParameters();
                for(int i = 0;i<paras.size();i++) {
                    pst.setObject(index++, paras.get(i));
                }
            }
            int result=pst.executeUpdate();
            flag = result > 0? true : false;
        } catch (SQLException e) {
            flag = false;
            e.printStackTrace();
        }finally {
            close(conn, pst);
        }
        return flag;    
    }
    /**
     * 获取单个对象 可用于登录注册验证
     * @param sql
     * @param paras
     * @param cls
     * @return
     */
    public static <T> T findBySingleObject(String sql,ArrayList<Object> paras,Class<T> cls) {
        Connection conn =getConnection();
        PreparedStatement pst = null;
        ResultSet rs=null;
        T singleObject = null;
        int index = 1;

        try {
            pst = conn.prepareStatement(sql);
            if(paras != null && paras.size()>0) {
                pst.clearParameters();   
                for(int i = 0;i<paras.size();i++) {
                    pst.setObject(index++,paras.get(i));
                }
            }
            rs = pst.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while(rs.next()) {
                singleObject = cls.newInstance();
                for(int i = 0;i<columnCount;i++) {
                    String columnName = rsmd.getColumnName(i+1);
                    Object columnValue = rs.getObject(columnName);
                    Field field = cls.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(singleObject, columnValue);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            close(conn, pst);

        }
        return singleObject;

    }
    /**
     * 
     * 列表查询
     */
    public static<T> List<T> queryListExecute(String sql,ArrayList<Object> paras,Class<T> cls ){
        Connection conn = getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        T singleObject = null;
        int index = 1;
        List <T> list = new ArrayList<T>();
        try {
            pst = conn.prepareStatement(sql);
            if(paras !=null && paras.size()>0) {
                pst.clearParameters();
                for(int i = 0;i<paras.size();i++) {
                    pst.setObject(index++, paras.get(i));
                }   
            }
            rs = pst.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while(rs.next()) {
                singleObject = cls.newInstance();
                for(int i = 0;i<columnCount;i++) {
                    String columnName = rsmd.getColumnName(i+1);
                    Object columdValue = rs.getObject(columnName);
                    Field field = cls.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(singleObject, columdValue);
                }
                list.add(singleObject);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            close(conn, pst, rs);
        }

        return list;
    }


    /*
     * 释放资源
     */
    public static void close(Connection conn, PreparedStatement pst) {
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, PreparedStatement pst,
            ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}   
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
224
225
db.properties

url = jdbc:mysql://localhost:3306/library?zeroDateTimeBehavior=convertToNull
username = root
password = 123456
Driver = com.mysql.jdbc.Driver
--------------------- 
作者:终末之光 
来源:优快云 
原文:https://blog.youkuaiyun.com/qxqx451/article/details/79422029 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值