티스토리 뷰

LANGUAGE/JAVA

[JAVA] DB연동

찰떡쿠키부스트 2017. 11. 15. 10:22

 

JAVA 에서 데이터베이스 연결

1. 드라이버 클래스 등록

​ex) Class.forName ("oracle.jdbc.driver.OracleDriver");

 

forname 메서드=클래스를 메모리에 로드시키는 역할(즉 OracleDriver클래스를 메모리에등록)
throws ClassNotFoundException 를 가지고있어서 처리해줘야됨.
오라클 클래스니까 classpath 해줘야됨 (set classpath=.;주소)

2. 연결 개체 만들기​ 

​ex) Connection conn = DriverManager.getConnection ("url","아이디","비밀번호");

DriverManager 클래스의  getConnection () 메소드는

데이터베이스와의 연결을 설정하는 데 사용


3. Statement 객체를 생성

ex) Statement stmt=conn.createStatement();


Statement - 쿼리문을 실행하게하는 인터페이스(객체생성을 못하므로
   위의 다형적 변수 conn을 이용해
   Connection 인터페이스의 createStatement () 메소드를 사용)

4. 쿼리 실행

ex) ResultSet rs=stmt.executeQuery("select * from emp");

Statement 인터페이스의 executeQuery () 메소드는 
데이터베이스에 대한 조회를 실행하는 데 사용하고  ResultSet 객체를 반환​ (select)

ex) int result=stmt.executeUpdate("delete from emp765 where id=33");  

Statement 인터페이스의 executeUpdate () 메소드는 
데이터베이스에 대한 조회를 실행하는 데 사용하고   int  객체를 반환​
​  ( insert, update, delete)

5) 연결 개체를 닫기

ex)conn.close ();


-->

자원정리( 오라클관련된건 끝나도 메모리에서 안지워지니까 지워주는거,역순으로지워줘야됨)
예외가 발생해서 실행이 다안되더라도 그거랑 상관없이 다 지워야되기때문에 finally 안에 넣음
finally실행전에 예외가발생하면 Nullpointexception 발생 그래서 if조건줌
가바지컬렉터가 쓰레기인줄 인식하기 위해 =null; 해줘야됨
근데 close 메서드도 Exception이 발생하니까 close도 try catch 해줘야됨


ex)

try{
 if(rs!=null){rs.close();rs=null;}
 if(stmt!=null){stmt.close();stmt=null;}
 if(conn!=null){conn.close();conn=null;}
 }catch(Exception e){

 }

 

 

예제)

 

public class DBUtil {
 public static Connection getConnection() throws Exception {
 Class.forName("oracle.jdbc.OracleDriver");
 /* class forName클래스는 클래스를 메모리에 로드시키는 역할
    (즉 OracleDriver클래스를 메모리에등록)
    throws ClassNotFoundException 를 가지고있어서 처리해줘야됨.
 오라클 클래스니까 classpath 해줘야됨 (set classpath=.;주소)  */
 String url = "jdbc:oracle:thin:@//localhost:1521/xe";
 Connection conn = DriverManager.getConnection(url, "scott", "tiger");
 return conn;
 /* DriverManager 클래스의 getConnection메소드는
     데이터베이스와의 연결을 설정하는데 사용 */
 }
}

 

 

DB연동 관련 메서드들.

public static Class<?> forName(String className)
                        throws ClassNotFoundException

public static Connection getConnection(String url,
                                       String user,
                                       String password)
                                throws SQLException

Statement createStatement()
                   throws SQLException
        

ResultSet executeQuery(String sql)
                throws SQLException

executeQuery()     ---> select

int executeUpdate(String sql)
           throws SQLException
executeUpdate()    ---> insert, update , delete

rs.next --> ResultSet에있는 커서다음으로 넘겨주는 메서드 (반환형 boolean)

rs.getString --> ResultSet에있는 dbms칼럼받아오는 메서드

public void printStackTrace(PrintStream s)
 -->Exception에있는 메서드 (어디서 Exception발생했는지 콘솔창에 역추적해서 보여줌)
 

PreparedStatement prepareStatement(String sql)
                            throws SQLException

--> insert, update , delete 쿼리문 작성할때 칼럼이 100개인데
    ' 이런거 한개 빠자먹으면 그거 일일이 찾아야되니까 PreparedStatement를
 이용해서 executeUpdate()를 이용하기전에 각자먼저 선언해줌.(원래자리에는 ? 사용)
 혹은 select문 쓸때도 쿼리문에 ? 사용해서 사용도 가능.
 
void close()
    throws SQLException
--> 자원정리( 오라클관련된건 끝나도 메모리에서 안지워지니까 지워주는거,역순으로지워줘야됨)
    예외가 발생해서 실행이 다안되더라도 그거랑 상관없이 다 지워야되기때문에 finally 안에 넣음
 finally실행전에 예외가발생하면 Nullpointexception 발생 그래서 if조건줌
 가바지컬렉터가 쓰레기인줄 인식하기 위해 =null; 해줘야됨
 근데 close 메서드도 Exception이 발생하니까 close도 try catch 해줘야됨 ​
 

 

'LANGUAGE > JAVA' 카테고리의 다른 글

[JAVA] String 객체  (0) 2017.11.15
[JAVA] Collection, 제네릭  (0) 2017.11.15
[JAVA] Exception  (1) 2017.11.15
[JAVA] java.awt패키지 관련  (0) 2017.11.15
[JAVA] 내부클래스  (0) 2017.11.15
댓글