Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.time.LocalDateTime;
- import java.util.ArrayList;
- import java.util.List;
- // java.timeをDBで利用
- // [前提条件]Oracle JDBCドライバはojdbc8.jar(Java8対応版)を使うこと
- // タイムサンプルテーブルは以下のとおり
- // 列名 データ型 制約
- // -----------------------------------
- // id number(2) 主キー
- // 日付 timestamp not null
- public class TimeDAO {
- private static final String CONNECTION_STR =
- "jdbc:oracle:thin:@//172.16.4.6:1521/infopdb";
- private static final String DB_USER = "demo2017";
- private static final String DB_PASSWD = "demo2017";
- public static int insert(int id) throws SQLException
- {
- int row = 0;
- try(
- Connection con =
- DriverManager.getConnection(CONNECTION_STR, DB_USER, DB_PASSWD);
- PreparedStatement pstmt = createPreparedStatement(con, id);
- )
- {
- row = pstmt.executeUpdate();
- }
- return row;
- }
- private static PreparedStatement createPreparedStatement(Connection con, int id) throws SQLException{
- PreparedStatement pstmt = con.prepareStatement("INSERT INTO タイムサンプル(id, 日付) values(?, ?)");
- pstmt.setInt(1, id);
- // 日付列はTimestamp型
- // SQL中のパラメータマーカーに値をバンドするには、PreparedStatementクラスのsetTimestamp()を使う
- // setTimestamp()の第2引数はjava.sql.Timestampクラス型
- // java.time.LocalDateTimeクラスのnow()メソッドの戻り値はLocalDateTimeクラス型
- // java.sql.TimestampクラスのvalueOf()メソッドでLocalDateTimeからjava.sql.Timestampへ変換を行う
- // valueOf()メソッドはJava8で追加
- pstmt.setTimestamp(2, Timestamp.valueOf(LocalDateTime.now()));
- return pstmt;
- }
- public static List<TimeSample> findAll() throws SQLException
- {
- List<TimeSample> list = new ArrayList<>();
- Connection con =
- DriverManager.getConnection(CONNECTION_STR, DB_USER, DB_PASSWD);
- Statement stmt = ((Connection) con).createStatement();
- ResultSet rs = ((Statement) stmt).executeQuery("SELECT id, 日付 FROM タイムサンプル order by 日付");
- while (((ResultSet) rs).next()) {
- // getTimestamp()の戻り値はjava.sql.Timestampクラス型
- // toLocalDateTime()でLocalDateTimeクラス型へ変換を行う
- // toLocalDateTime()メソッドはJava8で追加
- list.add(new TimeSample(
- rs.getInt("id"),
- rs.getTimestamp("日付").toLocalDateTime()
- ));
- }
- return list;
- }
- }
Add Comment
Please, Sign In to add comment