Guest User

Untitled

a guest
Jun 8th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. import java.sql.*;
  2. import java.time.LocalDateTime;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. // java.timeをDBで利用
  7. // [前提条件]Oracle JDBCドライバはojdbc8.jar(Java8対応版)を使うこと
  8. // タイムサンプルテーブルは以下のとおり
  9. // 列名 データ型 制約
  10. // -----------------------------------
  11. // id number(2) 主キー
  12. // 日付 timestamp not null
  13. public class TimeDAO {
  14. private static final String CONNECTION_STR =
  15. "jdbc:oracle:thin:@//172.16.4.6:1521/infopdb";
  16. private static final String DB_USER = "demo2017";
  17. private static final String DB_PASSWD = "demo2017";
  18.  
  19. public static int insert(int id) throws SQLException
  20. {
  21. int row = 0;
  22.  
  23. try(
  24. Connection con =
  25. DriverManager.getConnection(CONNECTION_STR, DB_USER, DB_PASSWD);
  26. PreparedStatement pstmt = createPreparedStatement(con, id);
  27. )
  28. {
  29. row = pstmt.executeUpdate();
  30. }
  31.  
  32. return row;
  33. }
  34.  
  35. private static PreparedStatement createPreparedStatement(Connection con, int id) throws SQLException{
  36. PreparedStatement pstmt = con.prepareStatement("INSERT INTO タイムサンプル(id, 日付) values(?, ?)");
  37. pstmt.setInt(1, id);
  38. // 日付列はTimestamp型
  39. // SQL中のパラメータマーカーに値をバンドするには、PreparedStatementクラスのsetTimestamp()を使う
  40. // setTimestamp()の第2引数はjava.sql.Timestampクラス型
  41. // java.time.LocalDateTimeクラスのnow()メソッドの戻り値はLocalDateTimeクラス型
  42. // java.sql.TimestampクラスのvalueOf()メソッドでLocalDateTimeからjava.sql.Timestampへ変換を行う
  43. // valueOf()メソッドはJava8で追加
  44. pstmt.setTimestamp(2, Timestamp.valueOf(LocalDateTime.now()));
  45.  
  46. return pstmt;
  47. }
  48.  
  49. public static List<TimeSample> findAll() throws SQLException
  50. {
  51. List<TimeSample> list = new ArrayList<>();
  52.  
  53. Connection con =
  54. DriverManager.getConnection(CONNECTION_STR, DB_USER, DB_PASSWD);
  55. Statement stmt = ((Connection) con).createStatement();
  56.  
  57. ResultSet rs = ((Statement) stmt).executeQuery("SELECT id, 日付 FROM タイムサンプル order by 日付");
  58.  
  59. while (((ResultSet) rs).next()) {
  60. // getTimestamp()の戻り値はjava.sql.Timestampクラス型
  61. // toLocalDateTime()でLocalDateTimeクラス型へ変換を行う
  62. // toLocalDateTime()メソッドはJava8で追加
  63. list.add(new TimeSample(
  64. rs.getInt("id"),
  65. rs.getTimestamp("日付").toLocalDateTime()
  66. ));
  67. }
  68.  
  69. return list;
  70. }
  71. }
Add Comment
Please, Sign In to add comment