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