JDBC를 연결하는 방법은 5가지 절차로 실행된다.
1. Driver Load를 시킨다.
2. DB에 연결시킨다.
3. 쿼리를 수행합니다.
4. DB의 연결을 끊습니다.
|
// 기본적으로 자바 vendor들이 만든 것을 가져다 쓰는 것이다.
import java.sql.*;
public class JDBCTEST
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet result = null;
// 1. DRIVER LOAD
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
// 2. DB CONNECTIVITY
try{
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.5:1521:orcl", "scott", "tiger");
}catch(SQLException sqle){
sqle.printStackTrace();
}
// 3. query
try{
stmt = conn.createStatement();
result = stmt.executeQuery("Select * From dept");
while(result.next()){
System.out.println(result.getInt(1) + " : " + result.getString(2) + " : " + result.getString(3));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally{
// 5. DB CLOSE
try{
if(result != null) result.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
}
|