-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDaoUtil.java
More file actions
268 lines (237 loc) · 7.68 KB
/
Copy pathDaoUtil.java
File metadata and controls
268 lines (237 loc) · 7.68 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package com.feeyo.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DaoUtil {
private final static Logger LOGGER = LoggerFactory.getLogger(DaoUtil.class);
//将查询结果封装成bean
private static <T> T autoBean(Class<T> clazz, ResultSet rs)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
T bean = clazz.newInstance();
try {
ResultSetMetaData rsmd = rs.getMetaData();
int columCount = rsmd.getColumnCount();
for (int i = 1; i <= columCount; i++) {
String columName = rsmd.getColumnName(i);
Object value = rs.getObject(i);
BeanUtils.setProperty(bean, columName, value);
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
}
return bean;
}
//将对象转成map
public static Map<String, Object> convertBean(Object bean)
throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class<? extends Object> type = bean.getClass();
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
map.put(propertyName, result);
} else {
map.put(propertyName, "");
}
}
}
return map;
}
//插入数据到数据库
private static boolean insertTableByMap(String tableName, Map<String, Object> params) {
StringBuffer key = new StringBuffer();
StringBuffer value = new StringBuffer();
Iterator<Entry<String, Object>> iter = params.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> element = iter.next();
key.append(element.getKey() + ",");
if (element.getValue() instanceof String) {
String keyValue = ((String) element.getValue()).trim();
if ("".equals(keyValue)) {
keyValue = null;
}
element.setValue(keyValue);
}
if(element.getValue() != null){
if(element.getValue() instanceof java.sql.Date)
value.append("to_date('" + element.getValue()+ "','yyyy-mm-dd'),");
else
value.append("'" + element.getValue() + "',");
}else {//如果key对应的值为null,则不应加在null两端加单引号,否则sql语句是错误的
value.append(element.getValue() + ",");
}
}
key.replace(key.length() - 1, key.length(), "");
value.replace(value.length() - 1, value.length(), "");
StringBuffer sql = new StringBuffer("insert into ");
sql.append(tableName);
sql.append("(").append(key).append(")");
sql.append(" values (").append(value).append(")");
Connection conn = null;
Statement stat = null;
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
stat = conn.createStatement();
int count = stat.executeUpdate(sql.toString());
conn.commit();
if (count < 0) {
return false;
}
} catch (SQLException e) {
if(conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
LOGGER.error(e1.getMessage());
}
}
LOGGER.error(e.getMessage());
} finally {
DBUtil.close(conn, stat);
}
return true;
}
public static boolean insertValue(String tableName, Object obj) {
try {
Map<String, Object> propertyMap = DaoUtil.convertBean(obj);
return DaoUtil.insertTableByMap(tableName, propertyMap);
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
| IntrospectionException e) {
LOGGER.error(e.getMessage());
}
return false;
}
public static <T> List<T> getTableValues(String tableName, Class<T> clazz) {
List<T> list = new ArrayList<T>();
StringBuffer sql = new StringBuffer();
sql.append("select * from ").append(tableName);
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql.toString());
while (rs.next()) {
T item = DaoUtil.autoBean(clazz, rs);
if (item != null)
list.add(item);
}
} catch (SQLException e) {
DBUtil.close(conn, stmt, rs);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return list;
}
public static boolean executeQuery(String sql) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
stat = conn.createStatement();
rs = stat.executeQuery(sql);
if(rs.next())
return true;
return false;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(conn, stat, rs);
}
}
public static boolean execute(String sql) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
stat = conn.createStatement();
boolean status = stat.execute(sql.toString());
conn.commit();
return status;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(conn, stat, rs);
}
}
public static <T> List<T> getSqlValues(String sql, Class<T> clazz) {
List<T> list = new ArrayList<T>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
T item = DaoUtil.autoBean(clazz, rs);
if (item != null)
list.add(item);
}
} catch (SQLException e) {
DBUtil.close(conn, stmt, rs);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return list;
}
//批量插入数据到Sqlite数据库
public static void insertBatchTable(String tableName, final List<Map<String,Object>> params) {
if (params.isEmpty()) {
return;
}
Map<String,Object> keyMap = params.get(0);
StringBuffer keyBuf = new StringBuffer();
StringBuffer valueBuf = new StringBuffer();
for(String key : keyMap.keySet())
keyBuf.append(key).append(",");
keyBuf.replace(keyBuf.length() - 1, keyBuf.length(), "");
StringBuffer sql = new StringBuffer("insert into ");
sql.append(tableName);
sql.append("(").append(keyBuf).append(")");
for(Map<String, Object> param :params) {
valueBuf.append(" SELECT ");
for(Object value : param.values()) {
if(value instanceof String)
valueBuf.append("'").append((String)value).append("',");
else if(value instanceof Integer) {
valueBuf.append((int)value).append(",");
}
}
valueBuf.setLength(valueBuf.length() - 1);
valueBuf.append(" UNION ALL ");
}
int index = valueBuf.toString().lastIndexOf("UNION ALL");
valueBuf.setLength(index);
sql.append(valueBuf.toString());
execute(sql.toString());
}
}