Created
June 24, 2014 15:43
-
-
Save gnosis23/3d060079fa709d90d462 to your computer and use it in GitHub Desktop.
transaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main; | |
| import java.sql.*; | |
| import java.util.Properties; | |
| /** | |
| * @author: bohao | |
| */ | |
| public class Jdbb { | |
| public Connection getConn() { | |
| Connection conn = null; | |
| try { | |
| Properties props = new Properties(); | |
| props.put("user", "root"); | |
| props.put("password", "1111"); | |
| conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", props); | |
| } catch (SQLException e) { | |
| System.out.println("error"); | |
| } | |
| return conn; | |
| } | |
| public void viewTable(Connection conn) throws SQLException { | |
| try (Statement stmt = conn.createStatement()) { | |
| ResultSet rs = stmt.executeQuery("SELECT name,age from users where id > '1'"); | |
| while (rs.next()) { | |
| String name = rs.getString("name"); | |
| int age = rs.getInt("age"); | |
| System.out.println(name + " " + age); | |
| } | |
| } catch (Exception e) { | |
| System.out.println("view error"); | |
| } | |
| } | |
| public void updateTable() throws SQLException{ | |
| Connection conn = getConn(); | |
| conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); | |
| conn.setAutoCommit(false); | |
| try (Statement stmt = conn.createStatement()) { | |
| viewTable(conn); | |
| try { | |
| Thread.sleep(10_000); | |
| } catch (InterruptedException e) { | |
| System.out.println("SIGINTR"); | |
| } | |
| viewTable(conn); | |
| conn.commit(); | |
| } catch (SQLException e) { | |
| conn.rollback(); | |
| } finally { | |
| conn.setAutoCommit(true); | |
| conn.close(); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| Jdbb bb = new Jdbb(); | |
| try { | |
| bb.updateTable(); | |
| } catch (SQLException e) { | |
| System.out.println(e.getMessage()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment