-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLHelper.java
More file actions
51 lines (43 loc) · 1.68 KB
/
SQLHelper.java
File metadata and controls
51 lines (43 loc) · 1.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
package webapp.sql;
import webapp.exceptions.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 <T> T execution(String sql, SqlExecution<T> runner) {
try (Connection conn = connectionFactory.getConnection();
PreparedStatement preparedStmt = conn.prepareStatement(sql)) {
return runner.execution(preparedStmt);
} catch (SQLException e) {
System.out.println("SQLException message: " + e.getMessage());
System.out.println("SQLException SQL state: " + e.getSQLState());
System.out.println("SQLException SQL error code: " + e.getErrorCode());
throw new StorageException("SQL command problem!");
}
}
public <T> T transactionalExecute(SqlTransaction<T> runner) {
try (Connection conn = connectionFactory.getConnection()) {
try {
conn.setAutoCommit(false);
T res = runner.execution(conn);
conn.commit();
return res;
} catch (SQLException e) {
conn.rollback();
throw ExceptionUtil.convertException(e);
}
} catch (SQLException e) {
throw new StorageException(e);
}
}
public interface SqlExecution<T> {
T execution(PreparedStatement st) throws SQLException;
}
public interface SqlTransaction<T> {
T execution(Connection con) throws SQLException;
}
}