-
Notifications
You must be signed in to change notification settings - Fork 2
/
CommitAndRollback.java
57 lines (45 loc) 路 1.45 KB
/
CommitAndRollback.java
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
package com.jayden.study.transaction;
import com.jayden.study.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC Commit and Rollback
*
* @author jayden-lee
*/
public class CommitAndRollback {
private static final String url = "jdbc:mysql://localhost:3306/mysql";
private static final String user = "user";
private static final String password = "password";
private static Connection connection;
public static void main(String[] args) {
try {
connection = JdbcUtils.getConnection(url, user, password);
// change auto commit status
connection.setAutoCommit(false);
// Execute update Query
updateQuery();
// Commit
connection.commit();
} catch (Exception e) {
try {
// Rollback
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
JdbcUtils.closeConnection(connection);
}
}
private static void updateQuery() throws SQLException {
String sql = "INSERT INTO testdb.employee VALUES (150, 'jayden-lee', 'IT', 4)";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (SQLException e) {
throw e;
}
}
}