forked from JavaOPs/basejava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlHelper.java
More file actions
43 lines (37 loc) · 1.41 KB
/
SqlHelper.java
File metadata and controls
43 lines (37 loc) · 1.41 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
package com.urise.webapp.sql;
import com.urise.webapp.exception.StorageException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SqlHelper {
private final ConnectionFactory connectionFactory;
public SqlHelper(String dbUrl, String dbUser, String dbPassword) {
this.connectionFactory = () -> DriverManager.getConnection(dbUrl, dbUser, dbPassword);
}
public <T> T transactionalExecute(SqlTransaction<T> executor) {
try (Connection conn = connectionFactory.getConnection()) {
try{
conn.setAutoCommit(false);//после выпонения не будет выполняться автоматический commit
T res =executor.execute(conn);
conn.commit();
return res;
}
catch (SQLException e){
conn.rollback();
throw e;
}
} catch (SQLException e) {
throw new StorageException(e);
}
}
public <T> T transactionExecute(ABlockOfCode<T> aBlockOfCode, String sqlQuery) {
try (Connection conn = connectionFactory.getConnection();
PreparedStatement ps = conn.prepareStatement(sqlQuery)
) {
return aBlockOfCode.execute(ps);
} catch (SQLException e) {
throw new StorageException(e);
}
}
}