一、获取元数据
1 | public class MetaDataTest { |
二、事务处理
1.事务属性
2.隔离级别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
163public class TransactionTest {
/**
* 测试事务的隔离级别 在 JDBC 程序中可以通过 Connection 的 setTransactionIsolation 来设置事务的隔离级别.
*/
@Test
public void testTransactionIsolationUpdate() {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
connection.setAutoCommit(false);
String sql = "UPDATE users SET balance = "
+ "balance - 500 WHERE id = 1";
update(connection, sql);
connection.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Test
public void testTransactionIsolationRead() {
String sql = "SELECT balance FROM users WHERE id = 1";
Integer balance = getForValue(sql);
System.out.println(balance);
}
// 返回某条记录的某一个字段的值 或 一个统计的值(一共有多少条记录等.)
public <E> E getForValue(String sql, Object... args) {
// 1. 得到结果集: 该结果集应该只有一行, 且只有一列
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1. 得到结果集
connection = JDBCTools.getConnection();
System.out.println(connection.getTransactionIsolation());
// connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return (E) resultSet.getObject(1);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JDBCTools.releaseDB(resultSet, preparedStatement, connection);
}
// 2. 取得结果
return null;
}
/**
* Tom 给 Jerry 汇款 500 元.
*
* 关于事务: 1. 如果多个操作, 每个操作使用的是自己的单独的连接, 则无法保证事务. 2. 具体步骤: 1). 事务操作开始前, 开始事务:
* 取消 Connection 的默认提交行为. connection.setAutoCommit(false); 2). 如果事务的操作都成功,
* 则提交事务: connection.commit(); 3). 回滚事务: 若出现异常, 则在 catch 块中回滚事务:
*/
@Test
public void testTransaction() {
Connection connection = null;
try {
connection = JDBCTools.getConnection();
System.out.println(connection.getAutoCommit());
// 开始事务: 取消默认提交.
connection.setAutoCommit(false);
String sql = "UPDATE users SET balance = "
+ "balance - 500 WHERE id = 1";
update(connection, sql);
int i = 10 / 0;
System.out.println(i);
sql = "UPDATE users SET balance = " + "balance + 500 WHERE id = 2";
update(connection, sql);
// 提交事务
connection.commit();
} catch (Exception e) {
e.printStackTrace();
// 回滚事务
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
JDBCTools.releaseDB(null, null, connection);
}
/*
* try {
*
* //开始事务: 取消默认提交. connection.setAutoCommit(false);
*
* //...
*
* //提交事务 connection.commit(); } catch (Exception e) { //...
*
* //回滚事务 try { connection.rollback(); } catch (SQLException e1) {
* e1.printStackTrace(); } } finally{ JDBCTools.releaseDB(null, null,
* connection); }
*/
// DAO dao = new DAO();
//
// String sql = "UPDATE users SET balance = " +
// "balance - 500 WHERE id = 1";
// dao.update(sql);
//
// int i = 10 / 0;
// System.out.println(i);
//
// sql = "UPDATE users SET balance = " +
// "balance + 500 WHERE id = 2";
// dao.update(sql);
}
public void update(Connection connection, String sql, Object... args) {
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.releaseDB(null, preparedStatement, null);
}
}
}
三、数据库连接池
数据库连接池的执行过程
优点
1.c3p01
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/**
* 1. 创建 c3p0-config.xml 文件,
* 参考帮助文档中 Appendix B: Configuation Files 的内容
* 2. 创建 ComboPooledDataSource 实例;
* DataSource dataSource =
* new ComboPooledDataSource("helloc3p0");
* 3. 从 DataSource 实例中获取数据库连接.
*/
@Test
public void testC3poWithConfigFile() throws Exception{
DataSource dataSource =
new ComboPooledDataSource("helloc3p0");
System.out.println(dataSource.getConnection());
ComboPooledDataSource comboPooledDataSource =
(ComboPooledDataSource) dataSource;
System.out.println(comboPooledDataSource.getMaxStatements());
}
@Test
public void testC3P0() throws Exception{
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:mysql:///dbname" );
cpds.setUser("root");
cpds.setPassword("123456");
System.out.println(cpds.getConnection());
}
c3p0.xml1
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<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="helloc3p0">
<!-- 指定连接数据源的基本属性 -->
<property name="user">root</property>
<property name="password">123456</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///dbname</property>
<!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">5</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">10</property>
<!-- C3P0 数据库连接池可以维护的 Statement 的个数 -->
<property name="maxStatements">20</property>
<!-- 每个连接同时可以使用的 Statement 对象的个数 -->
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
2.DBCP1
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/**
* 1. 加载 dbcp 的 properties 配置文件: 配置文件中的键需要来自 BasicDataSource
* 的属性.
* 2. 调用 BasicDataSourceFactory 的 createDataSource 方法创建 DataSource
* 实例
* 3. 从 DataSource 实例中获取数据库连接.
*/
@Test
public void testDBCPWithDataSourceFactory() throws Exception{
Properties properties = new Properties();
InputStream inStream = JDBCTest.class.getClassLoader()
.getResourceAsStream("dbcp.properties");
properties.load(inStream);
DataSource dataSource =
BasicDataSourceFactory.createDataSource(properties);
System.out.println(dataSource.getConnection());
// BasicDataSource basicDataSource =
// (BasicDataSource) dataSource;
//
// System.out.println(basicDataSource.getMaxWait());
}
/**
* 使用 DBCP 数据库连接池
* 1. 加入 jar 包(2 个jar 包). 依赖于 Commons Pool
* 2. 创建数据库连接池
* 3. 为数据源实例指定必须的属性
* 4. 从数据源中获取数据库连接
* @throws SQLException
*/
@Test
public void testDBCP() throws SQLException{
final BasicDataSource dataSource = new BasicDataSource();
//2. 为数据源实例指定必须的属性
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:mysql:///dbname");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//3. 指定数据源的一些可选的属性.
//1). 指定数据库连接池中初始化连接数的个数
dataSource.setInitialSize(5);
//2). 指定最大的连接数: 同一时刻可以同时向数据库申请的连接数
dataSource.setMaxActive(5);
//3). 指定小连接数: 在数据库连接池中保存的最少的空闲连接的数量
dataSource.setMinIdle(2);
//4).等待数据库连接池分配连接的最长时间. 单位为毫秒. 超出该时间将抛出异常.
dataSource.setMaxWait(1000 * 5);
//4. 从数据源中获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection.getClass());
connection = dataSource.getConnection();
System.out.println(connection.getClass());
connection = dataSource.getConnection();
System.out.println(connection.getClass());
connection = dataSource.getConnection();
System.out.println(connection.getClass());
Connection connection2 = dataSource.getConnection();
System.out.println(">" + connection2.getClass());
new Thread(){
public void run() {
Connection conn;
try {
conn = dataSource.getConnection();
System.out.println(conn.getClass());
} catch (SQLException e) {
e.printStackTrace();
}
};
}.start();
try {
Thread.sleep(5500);
} catch (InterruptedException e) {
e.printStackTrace();
}
connection2.close();
}
dbcp.properties1
2
3
4
5
6
7
8
9username=root
password=123456
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///dbname
initialSize=10
maxActive=50
minIdle=5
maxWait=5000
3.JDBC批量插入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@Test
public void testBatch(){
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = null;
try {
connection = JDBCTools.getConnection();
JDBCTools.beginTx(connection);
sql = "INSERT INTO customers VALUES(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
Date date = new Date(new java.util.Date().getTime());
long begin = System.currentTimeMillis();
for(int i = 0; i < 100000; i++){
preparedStatement.setInt(1, i + 1);
preparedStatement.setString(2, "name_" + i);
preparedStatement.setDate(3, date);
//"积攒" SQL
preparedStatement.addBatch();
//当 "积攒" 到一定程度, 就统一的执行一次. 并且清空先前 "积攒" 的 SQL
if((i + 1) % 300 == 0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
//若总条数不是批量数值的整数倍, 则还需要再额外的执行一次.
if(100000 % 300 != 0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - begin)); //569
JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
} finally{
JDBCTools.releaseDB(null, preparedStatement, connection);
}
}
@Test
public void testBatchWithPreparedStatement(){
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = null;
try {
connection = JDBCTools.getConnection();
JDBCTools.beginTx(connection);
sql = "INSERT INTO customers VALUES(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
Date date = new Date(new java.util.Date().getTime());
long begin = System.currentTimeMillis();
for(int i = 0; i < 100000; i++){
preparedStatement.setInt(1, i + 1);
preparedStatement.setString(2, "name_" + i);
preparedStatement.setDate(3, date);
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - begin)); //9819
JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
} finally{
JDBCTools.releaseDB(null, preparedStatement, connection);
}
}
/**
* 向 Oracle 的 customers 数据表中插入 10 万条记录
* 测试如何插入, 用时最短.
* 1. 使用 Statement.
*/
@Test
public void testBatchWithStatement(){
Connection connection = null;
Statement statement = null;
String sql = null;
try {
connection = JDBCTools.getConnection();
JDBCTools.beginTx(connection);
statement = connection.createStatement();
long begin = System.currentTimeMillis();
for(int i = 0; i < 100000; i++){
sql = "INSERT INTO customers VALUES(" + (i + 1)
+ ", 'name_" + i + "', '29-6月 -13')";
statement.addBatch(sql);
}
long end = System.currentTimeMillis();
System.out.println("Time: " + (end - begin)); //39567
JDBCTools.commit(connection);
} catch (Exception e) {
e.printStackTrace();
JDBCTools.rollback(connection);
} finally{
JDBCTools.releaseDB(null, statement, connection);
}
}
4.改变的JDBC工具类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
78public class JDBCTools {
//处理数据库事务的
//提交事务
public static void commit(Connection connection){
if(connection != null){
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//回滚事务
public static void rollback(Connection connection){
if(connection != null){
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//开始事务
public static void beginTx(Connection connection){
if(connection != null){
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static DataSource dataSource = null;
//数据库连接池应只被初始化一次.
static{
dataSource = new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
public static void releaseDB(ResultSet resultSet, Statement statement,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
//数据库连接池的 Connection 对象进行 close 时
//并不是真的进行关闭, 而是把该数据库连接会归还到数据库连接池中.
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
5.DBUtils1
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
220public class DBUtilsTest {
/**
* QueryLoader: 可以用来加载存放着 SQL 语句的资源文件.
* 使用该类可以把 SQL 语句外置化到一个资源文件中. 以提供更好的解耦
* @throws IOException
*/
@Test
public void testQueryLoader() throws IOException{
// / 代表类路径的根目录.
Map<String, String> sqls =
QueryLoader.instance().load("/sql.properties");
String updateSql = sqls.get("UPDATE_CUSTOMER");
System.out.println(updateSql);
}
/**
* 1. ResultSetHandler 的作用: QueryRunner 的 query 方法的返回值最终取决于
* query 方法的 ResultHandler 参数的 hanlde 方法的返回值.
*
* 2. BeanListHandler: 把结果集转为一个 Bean 的 List, 并返回. Bean 的类型在
* 创建 BeanListHanlder 对象时以 Class 对象的方式传入. 可以适应列的别名来映射
* JavaBean 的属性名:
* String sql = "SELECT id, name customerName, email, birth " +
* "FROM customers WHERE id = ?";
*
* BeanListHandler(Class<T> type)
*
* 3. BeanHandler: 把结果集转为一个 Bean, 并返回. Bean 的类型在创建 BeanHandler
* 对象时以 Class 对象的方式传入
* BeanHandler(Class<T> type)
*
* 4. MapHandler: 把结果集转为一个 Map 对象, 并返回. 若结果集中有多条记录, 仅返回
* 第一条记录对应的 Map 对象. Map 的键: 列名(而非列的别名), 值: 列的值
*
* 5. MapListHandler: 把结果集转为一个 Map 对象的集合, 并返回.
* Map 的键: 列名(而非列的别名), 值: 列的值
*
* 6. ScalarHandler: 可以返回指定列的一个值或返回一个统计函数的值.
*/
@Test
public void testScalarHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT name FROM customers " +
"WHERE id = ?";
try {
connection = JDBCTools.getConnection();
Object count = queryRunner.query(connection, sql,
new ScalarHandler(), 6);
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, connection);
}
}
@Test
public void testMapListHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT id, name, email, birth " +
"FROM customers";
try {
connection = JDBCTools.getConnection();
List<Map<String, Object>> mapList = queryRunner.query(connection,
sql, new MapListHandler());
System.out.println(mapList);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, connection);
}
}
@Test
public void testMapHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT id, name customerName, email, birth " +
"FROM customers WHERE id = ?";
try {
connection = JDBCTools.getConnection();
Map<String, Object> map = queryRunner.query(connection,
sql, new MapHandler(), 4);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, connection);
}
}
/**
* 测试 ResultSetHandler 的 BeanListHandler 实现类
* BeanListHandler: 把结果集转为一个 Bean 的 List. 该 Bean
* 的类型在创建 BeanListHandler 对象时传入:
*
* new BeanListHandler<>(Customer.class)
*
*/
@Test
public void testBeanListHandler(){
String sql = "SELECT id, name customerName, email, birth " +
"FROM customers";
//1. 创建 QueryRunner 对象
QueryRunner queryRunner = new QueryRunner();
Connection conn = null;
try {
conn = JDBCTools.getConnection();
Object object = queryRunner.query(conn, sql,
new BeanListHandler<>(Customer.class));
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, conn);
}
}
/**
* 测试 QueryRunner 的 query 方法
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testResultSetHandler(){
String sql = "SELECT id, name, email, birth " +
"FROM customers";
//1. 创建 QueryRunner 对象
QueryRunner queryRunner = new QueryRunner();
Connection conn = null;
try {
conn = JDBCTools.getConnection();
/**
* 2. 调用 query 方法:
* ResultSetHandler 参数的作用: query 方法的返回值直接取决于
* ResultSetHandler 的 hanlde(ResultSet rs) 是如何实现的. 实际上, 在
* QueryRunner 类的 query 方法中也是调用了 ResultSetHandler 的 handle()
* 方法作为返回值的。
*/
Object object = queryRunner.query(conn, sql,
new ResultSetHandler(){
@Override
public Object handle(ResultSet rs) throws SQLException {
List<Customer> customers = new ArrayList<>();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
Customer customer =
new Customer(id, name, email, birth);
customers.add(customer);
}
return customers;
}
}
);
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, conn);
}
}
/**
* 测试 QueryRunner 类的 update 方法
* 该方法可用于 INSERT, UPDATE 和 DELETE
*/
@Test
public void testQueryRunnerUpdate() {
//1. 创建 QueryRunner 的实现类
QueryRunner queryRunner = new QueryRunner();
String sql = "DELETE FROM customers " +
"WHERE id IN (?,?)";
Connection connection = null;
try {
connection = JDBCTools.getConnection();
//2. 使用其 update 方法
queryRunner.update(connection,
sql, 12, 13);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.releaseDB(null, null, connection);
}
}
}
sql.properties1
UPDATE_CUSTOMER=UPDATE customers SET name = ? WHERE id = ?
四、用Utils写一个dao
1.dao1
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/**
* 访问数据的 DAO 接口.
* 里边定义好访问数据表的各种方法
* @param T: DAO 处理的实体类的类型.
*/
public interface DAO<T> {
/**
* 批量处理的方法
* @param connection
* @param sql
* @param args: 填充占位符的 Object [] 类型的可变参数.
* @throws SQLException
*/
void batch(Connection connection,
String sql, Object [] ... args) throws SQLException;
/**
* 返回具体的一个值, 例如总人数, 平均工资, 某一个人的 email 等.
* @param connection
* @param sql
* @param args
* @return
* @throws SQLException
*/
<E> E getForValue(Connection connection,
String sql, Object ... args) throws SQLException;
/**
* 返回 T 的一个集合
* @param connection
* @param sql
* @param args
* @return
* @throws SQLException
*/
List<T> getForList(Connection connection,
String sql, Object ... args) throws SQLException;
/**
* 返回一个 T 的对象
* @param connection
* @param sql
* @param args
* @return
* @throws SQLException
*/
T get(Connection connection, String sql,
Object ... args) throws SQLException;
/**
* INSRET, UPDATE, DELETE
* @param connection: 数据库连接
* @param sql: SQL 语句
* @param args: 填充占位符的可变参数.
* @throws SQLException
*/
void update(Connection connection, String sql,
Object ... args) throws SQLException;
}
2.dao实现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/**
* 使用 QueryRunner 提供其具体的实现
* @param <T>: 子类需传入的泛型类型.
*/
public class JdbcDaoImpl<T> implements DAO<T> {
private QueryRunner queryRunner = null;
private Class<T> type;
public JdbcDaoImpl() {
queryRunner = new QueryRunner();
type = ReflectionUtils.getSuperGenericType(getClass());
}
@Override
public void batch(Connection connection, String sql, Object[]... args) throws SQLException {
queryRunner.batch(connection, sql, args);
}
@Override
public <E> E getForValue(Connection connection, String sql, Object... args) throws SQLException {
return (E) queryRunner.query(connection, sql, new ScalarHandler(), args);
}
@Override
public List<T> getForList(Connection connection, String sql, Object... args)
throws SQLException {
return queryRunner.query(connection, sql,
new BeanListHandler<>(type), args);
}
@Override
public T get(Connection connection, String sql, Object... args) throws SQLException {
return queryRunner.query(connection, sql,
new BeanHandler<>(type), args);
}
@Override
public void update(Connection connection, String sql, Object... args) throws SQLException {
queryRunner.update(connection, sql, args);
}
}
3.调用1
2
3
4
public class CustomerDao extends JdbcDaoImpl<Customer>{
}