-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlHelper.java
More file actions
44 lines (37 loc) · 1.32 KB
/
SqlHelper.java
File metadata and controls
44 lines (37 loc) · 1.32 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
package com.learnjava.sql;
import com.learnjava.exception.StorageException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SqlHelper {
private final ConnectionFactory connectionFactory;
public SqlHelper(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void execute(String sql) {
execute(sql, PreparedStatement::execute);
}
public <T> T execute(String sql, SqlExecutor<T> executor) {
try (Connection conn = connectionFactory.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
return executor.execute(ps);
} catch (SQLException e) {
throw ExceptionUtil.convertException(e);
}
}
public <T> T transactionalExecute(SqlTransaction<T> executor) {
try (Connection conn = connectionFactory.getConnection()) {
try {
conn.setAutoCommit(false);
T res = executor.execute(conn);
conn.commit();
return res;
} catch (SQLException e) {
conn.rollback();
throw ExceptionUtil.convertException(e);
}
} catch (SQLException e) {
throw new StorageException(e);
}
}
}