本例以mysql为例
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
/*
MySQL Data Transfer
Source Host: localhost
Source Database: test
Target Host: localhost
Target Database: test
Date: 2016/07/09 09:19:38
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user 创建表
-- ----------------------------
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(40) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records 填充数据
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张一', '1');
INSERT INTO `user` VALUES ('2', '张二', '2');
INSERT INTO `user` VALUES ('3', '张三', '3');
INSERT INTO `user` VALUES ('4', '张四', '4');
INSERT INTO `user` VALUES ('5', '张五', '5');
数据库配置文件jdbc.properties
1
2
3
4
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=root
Code
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
package test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
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.Properties;
import org.apache.tomcat.dbcp.dbcp.ConnectionFactory;
public class Test {
private static Properties prop;
private static Connection conn = null;
private static final String CONFIGNAME = "jdbc.properties";
public static void main(String[] args) {
// 打开数据库链接
getConnection();
try {
// 禁用自动提交
conn.setAutoCommit(false);
System.out.println("默认的事务隔离级别:" + conn.getTransactionIsolation());
// 用 conn 创建 Statement 对象类实例
Statement statement = conn.createStatement();
// 插入数据
statement.executeUpdate("insert user(id, username, password) values(6, '张六', '6')");
System.out.println("Insert Success");
System.out.println("------------------ 我是分割线 ---------------------");
// 提交事务
conn.commit();
// 查询的话不需要事务,用ResultSet类的对象,返回查询的结果
String sql = "select * from user where id = 1";
ResultSet result = statement.executeQuery(sql_pojo);
// 原生的打印结果
while (result.next()) {
int id = result.getInt("id");
String username = result.getString("username");
String password = result.getString("password");
System.out.println("id: " + id + " username: " + username + " password: " + password);
}
result = statement.executeQuery(sql_pojo);
// 转为bean
List<User> bean = getBeanList(result);
for (int i = 0; i < bean.size(); i++) {
System.out.println(bean.get(i).toString());
}
System.out.println("------------------ 我是分割线 ---------------------");
String sql_list = "select * from user";
result = statement.executeQuery(sql_list);
// 原生的打印结果
while (result.next()) {
int id = result.getInt("id");
String username = result.getString("username");
String password = result.getString("password");
System.out.println("id: " + id + " username: " + username + " password: " + password);
}
result = statement.executeQuery(sql_list);
// 转为list
List<User> list = getBeanList(result);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
} catch (SQLException e) {
if (conn != null){
// 事务回滚
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 关闭数据库链接
closeConnection();
}
}
/**
* 获取数据库连接
* @throws SQLException
*/
public static Connection getConnection() {
prop = new Properties();
try {
prop.load(ConnectionFactory.class.getClassLoader().getResourceAsStream(CONFIGNAME));
Class.forName(prop.getProperty("jdbc_driverClassName"));
conn = DriverManager.getConnection(
prop.getProperty("jdbc_url"),
prop.getProperty("jdbc_username"),
prop.getProperty("jdbc_password"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据库连接
* @throws SQLException
*/
public static void closeConnection() {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取实体类列表(将原生的数据库访问查询结果Result转为一个POJO)
* @param rs
* @return
* @throws SQLException
*/
public static <T> List<T> getBeanList(ResultSet rs) throws SQLException {
List retultList = resultSetToList(rs);
List<T> pojoList = new ArrayList<T>();
for(int i = 0; i < retultList.size(); i++) {
T t = (T) MapToBean(new User(), (Map) retultList.get(i));
pojoList.add(t);
}
return pojoList;
}
/**
* 将ResultSet封装成list 而每条记录对应一个实体Map
* @param rs 结果集
* @return
* @throws SQLException
*/
public static List resultSetToList(ResultSet rs) throws SQLException{
if(rs == null) {
return null;
}
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
List list = new ArrayList();
Map rowData;
while (rs.next()){
rowData = new HashMap(columnCount);
for (int i = 1; i <= columnCount; i++){
rowData.put(md.getColumnName(i),rs.getObject(i));
}
list.add(rowData);
}
return list;
}
/**
* @param bean 需要封装的vo
* @param map 需要转换的map
* @return 已经封装好数据的vo(object)
*/
public static Object MapToBean(Object bean, Map map) {
Map methods = new HashMap();
Method m[] = bean.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
Method method = m[i];
String methodName = method.getName().toUpperCase();
methods.put(methodName, method);
}
Iterator it = null;
String key = "";
it = map.keySet().iterator();
while (it.hasNext()) {
key = (String) it.next();
String name = "GET" + key.toUpperCase();
if (methods.containsKey(name)) {
Method setMethod = (Method) methods.get("SET" + key.toUpperCase());
try {
if(setMethod!=null){
Object[] obj=null;
obj=new Object[1];
obj[0]=map.get(key);
setMethod.invoke(bean, obj);
}
else{
continue;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return bean;
}
}
class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}
}

Console打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
默认的事务隔离级别:4
Insert Success
------------------ 我是分割线 ---------------------
id: 1 username: 张一 password: 1
User [id=1, username=张一, password=1]
------------------ 我是分割线 ---------------------
id: 1 username: 张一 password: 1
id: 2 username: 张二 password: 2
id: 3 username: 张三 password: 3
id: 4 username: 张四 password: 4
id: 5 username: 张五 password: 5
id: 6 username: 张六 password: 6
User [id=1, username=张一, password=1]
User [id=2, username=张二, password=2]
User [id=3, username=张三, password=3]
User [id=4, username=张四, password=4]
User [id=5, username=张五, password=5]
User [id=6, username=张六, password=6]

查询user表

1
select * from user

输出结果
| id | username | password |
| :——-: |:————-:| :——–:|
| 1 | 张一 | 1 |
| 2 | 张二 | 2 |
| 3 | 张三 | 3 |
| 4 | 张四 | 4 |
| 5 | 张五 | 5 |
| 6 | 张六 | 6 |