My DAO pattern (Java)

A memorandum for myself Since it may be used in the next project,

** The description of DAO pattern covered in this article is only for the process of database connection and full search. DB is H2 **

//Library installation
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 driver loading
            Class.forName("org.h2.Driver");
            //Connect to database
            conn = DriverManager.getConnection("jdbc:h2:file:C:/data/DAOSample","username","password");

            //SQL preparation
            String sql = "SELECT * FROM DAOSample"
            //Convert character SQL to a type that can be used in DB
            PreparedStatement ps = conn.preparedStatement(sql);

            //Execute SQL to get the dataset
            ResultSet rs = ps.executeQuery();
            //Display the acquired contents in a loop
            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:" + name);
                System.out.println("age:" + age);
            }
        //Exception handling
        }catch(SQLException e){
            e.printStackTrace();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }finally{
            //Database disconnection
            if(conn != null){
                try{
                    conn.close();
                }catch(SQLException e){
                    e.printStarckTrace();
                }
        }
    }
}

Recommended Posts

My DAO pattern (Java)
[Java] Strategy pattern
Java design pattern
java callback pattern
My DOM (Java)
[Java] Singleton pattern
My StAX (Java)
[Java] Adapter pattern
My Java reference
Java pattern memo
My Study Note (Java)
Builder pattern (Effective Java)
Java Lambda Command Pattern
Java design pattern summary
[Design pattern] Java core library
Enum Strategy pattern in Java
[Java] Draw a simple pattern
Java
My note: Introducing Java to Ubuntu
JNA (Java Native Access) pattern collection
Java
DAO
Java beginner design pattern (Factory Method pattern)
My thoughts on the equals method (Java)