暂无描述

MariaDBTransaction.java 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package kr.co.swh.lecture.database.java;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.SQLException;
  6. /**
  7. * <pre>
  8. * kr.co.swh.lecture.database.java
  9. * MariaDBTransaction.java
  10. *
  11. * 설명 :데이터베이스 트랜잭션 예제
  12. * </pre>
  13. *
  14. * @since : 2017. 10. 26.
  15. * @author : tobby48
  16. * @version : v1.0
  17. */
  18. public class MariaDBTransaction {
  19. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  20. static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/market";
  21. static final String USERNAME = "root";
  22. static final String PASSWORD = "xxxxxxxx";
  23. public static void main(String[] args) throws SQLException, ClassNotFoundException {
  24. Connection connection = null;
  25. PreparedStatement preparedStatementInsert = null;
  26. PreparedStatement preparedStatementUpdate = null;
  27. String insertTableSQL = "INSERT INTO STUDENT"
  28. + "(id, name) VALUES"
  29. + "(?,?)";
  30. String updateTableSQL = "UPDATE STUDENT SET name =? "
  31. + "WHERE id = ?";
  32. try{
  33. Class.forName(JDBC_DRIVER);
  34. connection = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
  35. System.out.println("MariaDB 연결.");
  36. connection.setAutoCommit(false);
  37. preparedStatementInsert = connection.prepareStatement(insertTableSQL);
  38. preparedStatementInsert.setInt(1, 301);
  39. preparedStatementInsert.setString(2, "돌샘");
  40. preparedStatementInsert.executeUpdate();
  41. preparedStatementUpdate = connection.prepareStatement(updateTableSQL);
  42. /* 정상처리 */
  43. // preparedStatementUpdate.setString(1, "소리");
  44. // preparedStatementUpdate.setInt(2, 168);
  45. /* 오류
  46. * 첫번째 쿼리가 수행되지 않음
  47. * */
  48. preparedStatementUpdate.setString(1, "소리");
  49. preparedStatementUpdate.executeUpdate();
  50. connection.commit();
  51. System.out.println("트랜잭션 정상처리");
  52. } catch (SQLException e) {
  53. System.out.println(e.getMessage());
  54. connection.rollback();
  55. } finally {
  56. if (preparedStatementInsert != null) preparedStatementInsert.close();
  57. if (preparedStatementUpdate != null) preparedStatementUpdate.close();
  58. if (connection != null) connection.close();
  59. }
  60. System.out.println("MariaDB 연결종료.");
  61. }
  62. }