自分用の備忘録
次の案件で使う可能性があるので、
この記事で扱う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();
}
}
}
}