1
2

More than 3 years have passed since last update.

僕のDAOパターン(Java)

Posted at

自分用の備忘録
次の案件で使う可能性があるので、

この記事で扱うDAOパターンの記述は、データベース接続と全件検索を行う課程のみ。DBはH2

//ライブラリインストール
import java.sql.Connection;
import java.sql.DriverManger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DAOSample{
    public static void main(String[] args){
        Connection conn = null;
        try{
            //JDBCドライバー読み込み
            Class.forName("org.h2.Driver");
            //データベースへの接続
            conn = DriverManager.getConnection("jdbc:h2:file:C:/data/DAOSample","username","password");

            //SQL準備
            String sql = "SELECT * FROM DAOSample"
            //文字のSQLをDBで使用できる型に変換
            PreparedStatement ps = conn.preparedStatement(sql);

            //SQLを実行してデータセットを取得
            ResultSet rs = ps.executeQuery();
            //取得された内容をループさせて表示
            while(rs.next()){
                String id = rs.getString("ID");
                String name = rs.getString("NAME")
                int age = rs.getString("AGE")

                System.out.println("ID:" + id);
                System.out.println("名前:" + name);
                System.out.println("年齢:" + age);
            }
        //例外処理
        }catch(SQLException e){
            e.printStackTrace();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }finally{
            //データベース切断
            if(conn != null){
                try{
                    conn.close();
                }catch(SQLException e){
                    e.printStarckTrace();
                }
        }
    }
}

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2