db접속 정보를 저장한 db.properties파일을 읽어오기

 

- db.properties 파일에 db접속과 관련된 정보를 넣어둔다. 접속 시 파일을 읽어서 내용을 가져온다.

 

 

EX> db.properties

## Database Connect Info
url=jdbc:oracle:thin:@127.0.0.1:1521:xe
user=hr
pwd=hr

 

 

EX> Test05_Properties.java

package test01.jdbc;

 

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

 

class MyJdbc05{
    Connection con;
    public MyJdbc05() {

        Properties prop=new Properties();

        try{
            //db접속 정보를 저장한 db.properties파일을 읽어오기
            Reader reader=new FileReader("db.properties");
           
            //prop객체가 properties파일을 읽어와 Key와 Value형태로 분리해서 Map에 저장함.
           prop.load(reader);

            //Key에 해당하는 Value값 얻어오기
            String url=prop.getProperty("url");
            String user=prop.getProperty("user");
            String pwd=prop.getProperty("pwd");

            System.out.println("url==>" + url);
            System.out.println("user==>" + user);
            System.out.println("pwd==>" + pwd);
           
            // 설정된 정보로 db접속하기
            Class.forName("oracle.jdbc.OracleDriver");
            con=DriverManager.getConnection(url,user,pwd);
            System.out.println("db접속성공 ");
            System.out.println("con:" + con);
        }catch(FileNotFoundException fe){
            System.out.println(fe.getMessage());
        }catch(IOException ie){
            System.out.println(ie.getMessage());
        }catch(Exception ce){
            System.out.println(ce.getMessage());
        }
    }
}
public class Test05_Properties {
    public static void main(String[] args) {
        new MyJdbc05();
    }
}

 

 

 

 

1. CallableStatement

 

- PreparedStatement를 상속받은 인터페이스로 저장프로시져를 호출하는 기능을 갖음.

 

 

2. 테스트

 

1) 프로시져 생성.

 

PROCEDURE MEMPROC

CREATE OR REPLACE PROCEDURE MEMPROC
(
  ID MEMBERS.ID%TYPE,
  PWD VARCHAR2,
  EMAIL VARCHAR2,
  PHONE VARCHAR2
)
IS

BEGIN

  INSERT INTO MEMBERS
  VALUES(ID,PWD,EMAIL,PHONE,SYSDATE);
  
  COMMIT;

END ;

/

 

 

EX> DB접속 CLASS

 

DBConnection.java

package test.db;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

 

public class DBConnection {
    public static Connection getCon() throws SQLException{
        Connection con=null;
        try{
            Class.forName("oracle.jdbc.OracleDriver");
            String url="jdbc:oracle:thin:@localhost:1521:XE";
            con= DriverManager.getConnection(url,"scott","tiger");
            return con;
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
            return null;
        }
    }
}

 

 EX> 프로시져 호출하기.

Test01.java

package test01.jdbc;

 

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import test.db.DBConnection;

 

class MyJdbc01{
    public  MyJdbc01()  {
        Connection con=null;
        CallableStatement  cstmt=null;
       
        try{
            con=DBConnection.getCon();
            System.out.println("db접속성공!");

            //String  sql="{call  프로시져명(파라미터,...)}";
            String  sql="{call  memproc(?,?,?,?)}";
            cstmt=con.prepareCall(sql);

            //?에  대응되는  파라미터값들  넣기
            cstmt.setString(1,"yb");
            cstmt.setString(2,"8765");
            cstmt.setString(3,"yb@naver.com");
            cstmt.setString(4,"010-111-1111");

            //프로시져호출하기
            cstmt.execute();
            System.out.println("프로시져가  성공적으로  호출되었어요!");
        }catch(SQLException se){   
            System.out.println(se.getMessage());   
        }finally{
            try{
                if(cstmt!=null)  cstmt.close();   
                if(con!=null)  con.close();
            }catch(SQLException  se){
                System.out.println(se.getMessage());
            }
        }
    }
}
public class Test01{
    public static void  main(String[]  args)  {   
        new MyJdbc01();   
    }
}

 

 

 

 

 

 

3. 동적 커서

 

- 리졀트셋 커서를 앞뒤로 자유롭게 이동. 기본적으로 커서는 앞으로만 이동할수 있고 읽기전용으로 설정되어 있음.

 


- 설정방법

 

Statement stmt= con.createStatement(

ResultSet.TYPE_SCROLL_INSENSITIVE,//커서이동방법

ResultSet.CONCUR_UPDATABLE //수정가능한 모드

);

 

EX> Test02.java

package test01.jdbc;

 

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import test.db.DBConnection;

 

class MyJdbc02{
    public MyJdbc02() {

 

        Connection con=null;
        Statement stmt=null;
        ResultSet rs=null;

 

        try{
            con=DBConnection.getCon();
            System.out.println("db접속성공!");
            //Statement createStatement(int resultSetType,
            //int resultSetConcurrency) throws SQLException
       
            stmt=con.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,//커서앞뒤로이동가능
                ResultSet.CONCUR_UPDATABLE //수정가능한 모드
            );
       
            String sql="select id,pwd,email,phone,regdate " +
              "from members "+
              "order by regdate desc";
            rs=stmt.executeQuery(sql);
            System.out.println("<< 앞에서부터 출력 >>");
            while(rs.next()){
                //문자열을 전체 10자리로 출력.출력방향은 왼쪽기준(왼쪽정렬)
                System.out.printf("%-10s",rs.getString(1));
                System.out.printf("%-10s",rs.getString(2));
                System.out.printf("%-15s",rs.getString(3));
                System.out.printf("%-15s",rs.getString(4));
                System.out.printf("%-15s\n",rs.getString(5));
            }
            System.out.println("<< 뒤에서부터 출력 >>");
            while(rs.previous()){
                //문자열을 전체 10자리로 출력.출력방향은 왼쪽기준(왼쪽정렬)
                System.out.printf("%-10s",rs.getString(1));
                System.out.printf("%-10s",rs.getString(2));
                System.out.printf("%-15s",rs.getString(3));
                System.out.printf("%-15s",rs.getString(4));
                System.out.printf("%-15s\n",rs.getString(5));
            }
            rs.absolute(1);//맨첫번째 행으로 이동
            rs.deleteRow();//현재행을 삭제
            System.out.println("첫번째 데이터가 삭제되었어요!!!");
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }finally{
            try{
                if(rs!=null) rs.close();
                if(stmt!=null) stmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){}
        }
    }
}

public class Test02 {
    public static void main(String[] args) {
        new MyJdbc02();
    }
}

 

 

 

 

1. 트랜잭션 처리

 

1) 트랜잭션:분리되어서는 안되는 연속적으로 처리되어야 할 작업 단위.

 

2) JDBC에서의 트랜잭션 처리
  JDBC에서는 자동커밋이 기본으로 설정되어 있음. 트랜잭션 처리를 하려면 Connection객체에서 설정한다.
 

    Connection con= ...
     con.setAutoCommit(false);//자동커밋해제
     ...
     con.commit();//커밋하기
     또는
     con.rollback();//작업취소하기

 

 

 

 

2. 테스트

1) 테이블

 

members 테이블


 drop table MEMBERS cascade constraints;

 


 CREATE TABLE MEMBERS(

    ID VARCHAR2(10) PRIMARY KEY,

    PWD VARCHAR2(10),

    EMAIL VARCHAR2(15),

    PHONE VARCHAR2(20),

    REGDATE DATE);

 

2) 자바

 

ex> members테이블에 insert하기. auto commit이 true아님.

Test03.java

package test01.jdbc;

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


class MyJdbc03{
    public MyJdbc03() {
        Connection con = null;
        Statement stmt = null;

 

        try{
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            con = DriverManager.getConnection(url, "scott", "tiger");

 

            System.out.println("dbms 접속성공");

 

            stmt = con.createStatement();
           
            con.setAutoCommit(false);
           
            String sql  = "INSERT INTO MEMBERS VALUES ('hong1','1','song1','000', sysdate )";
            String sql1 = "INSERT INTO MEMBERS VALUES ('lee1','1','song1@fjd','000', sysdate )";
           
            stmt.executeUpdate(sql);
            stmt.executeUpdate(sql1);
           
            con.commit();
            System.out.println("데이터 추가 성공");
           
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException e){
            System.out.println(e.getMessage());
            try{
                con.rollback();
                System.out.println("오류로 인해서 작업이 취소되었습니다.");
            }catch(SQLException se){
                System.out.println(se.getMessage());
            }
        }finally{
            try{
                if(stmt!=null) stmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){
               
            }
        }
    }
}
public class Test03 {
    public static void main(String[] args) {
        new MyJdbc03();
    }
}

 

 


EX>

ID,PWD,E-MAIL,포인트 를 입력받아 DB에 저장하고, 조회하기. (transaction 처리)

 

테이블, sequence 생성.

point 테이블


CREATE TABLE POINT(

NUM NUMBER PRIMARY KEY,

POINT NUMBER(5),

ID VARCHAR2(10) REFERENCES MEMBERS(ID)

);

 

 

CREATE SEQUENCE POINT_SEQ;

 

 

Test04.java

package test01.jdbc;

 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import test.db.DBConnection;

 


class MyJdbc04{
    Connection con;
    public MyJdbc04(){
        try{
            con=DBConnection.getCon();
            con.setAutoCommit(false);

            System.out.println("DB접속 성공!");
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }
    public void disConnect(){
        try{
            if(con!=null) con.close();
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }
    public void insert(){
        Scanner scan = new Scanner(System.in);


        System.out.println("회원아이디");
        String id = scan.next();
        System.out.println("회원비밀번호");
        String pwd = scan.next();
        System.out.println("회원이메일");
        String email = scan.next();
        System.out.println("회원전화번호");
        String phone = scan.next();

        System.out.println("적립할 포인트점수");
        int point = scan.nextInt();

 


        String sql1 = "insert into members values (?,?,?,?,sysdate)";
        String sql2 = "insert into point values (point_seq.nextval,?,?)";

 


        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;


        try{
            pstmt1 = con.prepareStatement(sql1);
            pstmt2 = con.prepareStatement(sql2);


            pstmt1.setString(1, id);
            pstmt1.setString(2, pwd);
            pstmt1.setString(3, email);
            pstmt1.setString(4, phone);
            pstmt1.executeUpdate();

 


            pstmt2.setInt(1, point);
            pstmt2.setString(2, id);
            pstmt2.executeUpdate();

 


            con.commit();
            System.out.println("회원가입이 성공적으로 이루어 졌습니다.");

        }catch(SQLException e){
            System.out.println(e.getMessage());
            try{
                con.rollback();
                System.out.println("오류가 발생되어 회원가입에 실패했습니다.");
            }catch(SQLException s){
                System.out.println(s.getMessage());
            }
        }
    }
    public void showList(){
        PreparedStatement pstmt =null;
        ResultSet rs = null;
       
        String sql = "select m.id  as id, m.pwd  as pwd, m.email  as email, p.point as point from members m, point p where m.id = p.id";
        try{
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
           
            while(rs.next()){
                System.out.println( "id: " + rs.getString("id"));
                System.out.println( "pwd: " + rs.getString("pwd"));
                System.out.println( "email: " + rs.getString("email"));
                System.out.println( "email: " + rs.getInt("point"));
            }
        }catch(SQLException e){
            System.out.println(e.getMessage());
        }finally{
            try{
                if(pstmt!=null) pstmt.close();
                if(rs!=null) rs.close();
            }catch(SQLException e){
                System.out.println(e.getMessage());
            }
        }
    }
}
public class Test04 {
    public static void main(String[] args) {
        MyJdbc04 mj = new MyJdbc04();

        mj.insert();
        mj.showList();
        mj.disConnect();
    }
}

 

 

 

 

properties파일에서 정보읽기


EX> db.properties파일에서 접속 정보 읽어와서 DB접속하기.

 


db.properties

## Database Connect Info

url=jdbc:oracle:thin:@127.0.0.1:1521:xe

user=hr

pwd=hr

 

Test05_Properties.java

package test01.jdbc;

 

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import test.db.DBConnection;

 

class MyJdbc05{
    Connection con = null;
    public MyJdbc05(){
        Properties prop = new Properties();
        Connection con = null;
        try{
            Reader reader = new FileReader("db.properties");
            prop.load(reader);
            String url = prop.getProperty("url");
            String user = prop.getProperty("user");
            String pwd = prop.getProperty("pwd");
           
            System.out.println("url:" + url + " user:" + user + " pwd:" + pwd);
           
            Class.forName("oracle.jdbc.OracleDriver");
            con = DriverManager.getConnection(url, user, pwd);
            System.out.println("dbms 접속성공");
            System.out.println("con:" + con);
        } catch(SQLException se){
           
        } catch (ClassNotFoundException ce) {
            // TODO: handle exception
        } catch( FileNotFoundException fe){
           
        } catch( IOException ie){
           
        }
       
    }
}
public class Test05_Properties {
    public static void main(String[] args) {
        MyJdbc05 jm = new MyJdbc05();
    }
}

 

 

1. preparedStatement

 

- statement를 상속받는 인터페이스로 SQL구문을 실행시키는 기능을 갖는 객체

 

- 사용방법
 SQL문장에 변수가 들어가야 할 부분을 ?로 넣고, 실행시 ?에 대응 되는 값을 setXXX메소드를 통해 설정한다.

 

- 특징
1) statement객체는 실행시 sql명령어를 지정하여 여러 sql구문을 하나의 statement객체로 수행이 가능하다.(재사용 가능)
 하지만, preparedStatement는 객체 생성시에 지정된 sql명령어만을 실행할수 있다.

 (다른 sql구문은 실행못함 ->재사용 못함)


2) 동일한 sql구문을 반복 실행한다면 preparedStatement가 성능면에서 빠름.

 

3) preparedStatement가 Statement보다 보안성이 좋다.

 

 

 

 

 

2. 테스트

 

1) 테이블
members

 

 drop table MEMBERS cascade constraints;


 CREATE TABLE MEMBERS(

    ID VARCHAR2(10) PRIMARY KEY,

    PWD VARCHAR2(10),

    EMAIL VARCHAR2(15),

    PHONE VARCHAR2(20),

    REGDATE DATE);

 

 

 

2) 자바소스

 

EX> 접속 후 preparedStatement로 입력,수정,삭제 등 간단히 테스트 하기.

Test01.java

package test01.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

 


class MyJdbc01{
    public MyJdbc01(){


        Connection con=null;
        PreparedStatement pstmt=null;
        PreparedStatement pstmt1=null;
        PreparedStatement pstmt2=null;
        int n = 0;


        try{
            //1.드라이버로딩
            Class.forName("oracle.jdbc.OracleDriver");


            //2.컨넥션객체 얻어오기
            String url="jdbc:oracle:thin:@localhost:1521:XE";
            con=DriverManager.getConnection(url,"scott","tiger");
            System.out.println("db접속완료");

 

            String sql="insert into members values(?,?,?,?,sysdate)";

 

            //sql구문을 실행시키기 위한 prearestatement 객체 얻어오기
            pstmt=con.prepareStatement(sql);

 

            //?에 대응되는 값을 setXXX메소드로 지정하기
            pstmt.setString(1, "popo2");//1번째 ?에 yyy넣기
            pstmt.setString(2, "0707");//2번째 ? 에 0707넣기
            pstmt.setString(3, "yyy@naver");//3번째 ? 에 yyy@naver넣기
            pstmt.setString(4, "010-111-1111");//4번째 ? 에 010-111-1111넣기

 

            //sql 구문 실행
            n=pstmt.executeUpdate();
            System.out.println(n+"개의 데이터 추가");
           
            String sql1 = "DELETE FROM MEMBERS WHERE ID=?";


            pstmt1 = con.prepareStatement(sql1);
            pstmt1.setString(1, "yyy");
            n = pstmt1.executeUpdate();
            System.out.println(n+"개의 데이터 삭제");
           
            String sql2 = "UPDATE MEMBERS SET PWD=?,EMAIL=?,PHONE=? WHERE ID=?";
            pstmt2 = con.prepareStatement(sql2);
            pstmt2.setString(1, "1");
            pstmt2.setString(2, "2");
            pstmt2.setString(3, "3");
            pstmt2.setString(4, "popo2");
            n = pstmt2.executeUpdate();
            System.out.println(n+"개의 데이터 수정");
           
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }finally{
            try{
                if(pstmt!=null) pstmt.close();
                if(pstmt1!=null) pstmt1.close();
                if(con!=null) con.close();
            }catch(SQLException se){
                System.out.println(se.getMessage());
            }
        }
    }
}

public class Test01 {
    public static void main(String[] args) {
        new MyJdbc01();
    }
}

 

 

EX> 전체조회하기, 아이디를 입력받아 입력,삭제,조회하기.

 Test02.java

package test01.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Scanner;


class MyJdbc02{
    Connection con;
    Scanner scan = new Scanner(System.in);
   
    public MyJdbc02(){
        try{
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
           
            con = DriverManager.getConnection(url,"scott","tiger");
            System.out.println("db접속");
           
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException e){
            System.out.println(e.getMessage());
        }
    }


    public void disconnect() throws SQLException{
        if(con!=null) con.close();
    }
   
    public void showList() throws SQLException{
        PreparedStatement pstmt = null;
        ResultSet rs = null;
       
        String sql = "SELECT * FROM MEMBERS";
        pstmt = con.prepareStatement(sql);
        rs = pstmt.executeQuery();


        while(rs.next()){
            String id = rs.getString("id");
            String pwd = rs.getString("pwd");
            String email = rs.getString("email");
            String phone = rs.getString("phone");
           
            Timestamp regdate = rs.getTimestamp("regdate");
           
            System.out.println(id + "\t" + pwd + "\t" + email + "\t" + phone + "\t" + regdate );
        }
        if(rs!=null) rs.close();
        if(pstmt !=null) pstmt.close();
    }
   
    // 아이디를 입력받아 해당 정보를 삭제하기.
    public void delete() throws SQLException{
        PreparedStatement pstmt = null;
        System.out.println("아이디를 입력받아 해당 정보를 삭제하는 메소드");
        System.out.println("아이디>");
        String id = scan.next();
       
        String sql = "DELETE FROM MEMBERS WHERE ID=?";


        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, id);
        int n = pstmt.executeUpdate();
    }

   

    // 아이디, 비밀번호, 이메일, 전화번호를 입력받아 추가하는 메소드 만들기
    public void insert() throws SQLException{
        PreparedStatement pstmt = null;
        System.out.println("아이디, 비밀번호, 이메일, 전화번호를 입력받아 추가하는 메소드");
        System.out.println("아이디>");
        String id = scan.next();
        System.out.println("비밀번호>");
        String pwd = scan.next();
        System.out.println("이메일>");
        String email = scan.next();
        System.out.println("전화번호>");
        String phone = scan.next();
       
        String sql="INSERT INTO MEMBERS VALUES (?,?,?,?,SYSDATE)";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, id);
        pstmt.setString(2, pwd);
        pstmt.setString(3, email);
        pstmt.setString(4, phone);
       
        int n = pstmt.executeUpdate();
    }

 


    // 아이디를 입력받아 해당정보를 출력하는 메소드 만들기
    public void getInfo() throws SQLException{
        PreparedStatement pstmt = null;
        ResultSet rs = null;
       
        String sql ="SELECT * FROM MEMBERS WHERE ID=?";
        System.out.println("아이디를 입력받아 해당정보를 출력하는 메소드");
        System.out.println("아이디>");
        String id = scan.next();
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        System.out.println( "ID:"    + rs.getString("id")    + "\t" +
                            "PWD:"   + rs.getString("pwd")   + "\t" +
                            "EMAIL:" + rs.getString("email") + "\t" +
                            "PHONE:" + rs.getString("phone")  );
    }
}
public class Test02 {
    public static void main(String[] args) {
        MyJdbc02 mj = new MyJdbc02();
        try{
            mj.showList();
            mj.insert();
            mj.delete();
            mj.getInfo();
        }catch(SQLException e){
            System.out.println(e.getMessage());
        }finally{
            try {
                mj.disconnect();
            } catch (Exception e2) {
            }
        }
    }
}

 

members 테이블

 drop table MEMBERS cascade constraints;


 CREATE TABLE MEMBERS(

    ID VARCHAR2(10) PRIMARY KEY,

    PWD VARCHAR2(10),

    EMAIL VARCHAR2(15),

    PHONE VARCHAR2(20),

    REGDATE DATE);

 

 

 

EX> DB접속 후 Members테이블에 입력받은 값을 입력, 수정, 삭제, 조회하기.

 

Test02.java

package test01.jdbc;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;


class MyJdbc02{


    Connection con;
    Statement stmt;

 

    Scanner scan=new Scanner(System.in);


    public MyJdbc02() {
        try{
            //드라이버로딩
            Class.forName("oracle.jdbc.OracleDriver");

            String url="jdbc:oracle:thin:@localhost:1521:XE";

 

            //db접속및 컨넥션객체 얻어오기
            con=DriverManager.getConnection(url,"scott","tiger");
            System.out.println("db접속성공!");

 


            //sql구문을 실행하기위한 객체 얻어오기
            stmt=con.createStatement();
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }
    }

 

    //DB접속 해제
    public void disconnect() throws SQLException{
        if(stmt!=null) stmt.close();
        if(con!=null) con.close();
    }
   
    //키보드로 데이터 입력받아 추가하기
    public void insert() throws SQLException{

 

        //키보드로 데이터 입력받기
        System.out.println("아이디입력");
        String id=scan.next();
        System.out.println("비밀번호입력");
        String pwd=scan.next();
        System.out.println("이메일입력");
        String email=scan.next();
        System.out.println("전화번호입력");
        String phone=scan.next();


        //입력된 데이터 db에 저장하기
        //String sql="insert into members " +
        //           "values('id','pwd','email','phone',sysdate)";
        //변수는 ""밖으로 빠져야 한다.

 

        String sql="insert into members values('" +
                     id +"','" +
                     pwd +"','" +
                     email +"','" +
                     phone +"',sysdate)";

 

        int n=stmt.executeUpdate(sql)    ;

 

        System.out.println(n+"개의 데이터가 성공적으로 추가되었어요!");
    }

 

    public void delete() throws SQLException{


        //삭제할 아이디 키보드로 입력받기
        System.out.println("삭제할 아이디 입력");
        String id=scan.next();

        String sql="delete from members where id='" +id +"'";

 

        //sql구문 실행하기(삭제)
        int n=stmt.executeUpdate(sql);

 

        System.out.println(n+"개의 데이터가 성공적으로 삭제됨!");
    }

 

    //수정할 아이디를 입력받아 이멜과 전화번호를 수정해 보세요.
    public void update() throws SQLException{
        System.out.println("수정할 아이디 입력");
        String id=scan.next();
        System.out.println("새로운 이멜 입력");
        String email=scan.next();
        System.out.println("새로운 전화번호 입력");
        String phone=scan.next();

 

        String sql="update members "+
                   "set email='" +email +"',phone='" + phone +"' " +
                   "where id='" +id +"'";


        int n=stmt.executeUpdate(sql);

 

        System.out.println(n+"개의 데이터 수정성공!");
    }

 

    //전체 데이터를 출력하는 메소드 추가
    public void showMembers() throws SQLException{
       
    }
}


public class Test02 {
    public static void main(String[] args) {
        MyJdbc02 mj=new MyJdbc02();//생성되면서 생성자에서 db에 접속
        try{
            mj.insert();//데이터 추가하기
            mj.delete();//데이터 삭제하기
            mj.update();
            //mj.showMembers();
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }finally{
            try{
                mj.disconnect();//db접속해제하기
            }catch(SQLException se){
                System.out.println(se.getMessage());
            }
        }
    }
}

 

 

 

ex> SELECT 후 화면에 출력하기.

Test03.java


package test01.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;


class MyJdbc03{
    public MyJdbc03() {
        Connection con=null;
        Statement stmt=null;
        ResultSet rs=null;
        try{
            Class.forName("oracle.jdbc.OracleDriver");

            String url="jdbc:oracle:thin:@localhost:1521:xe";
            con=DriverManager.getConnection(url,"scott","tiger");


            System.out.println("db접속성공!");


            stmt=con.createStatement();

 

            String sql="select * from members";
            rs=stmt.executeQuery(sql);

 

            //다음행으로 이동
            while(rs.next()){
                //현재행의 id컬럼의 값 얻어오기
                String id=rs.getString("id");

                //현재행의 pwd컬럼의 값 얻어오기
                String pwd=rs.getString("pwd");

                //현재행의 email컬럼의 값 얻어오기
                String email=rs.getString("email");

                //현재행의 phone컬럼의 값 얻어오기
                String phone=rs.getString("phone");

                //현재행의 regdate컬럼의 값 얻어오기
                Date regdate=rs.getDate("regdate");

 


                System.out.println("아이디:" + id);
                System.out.println("비밀번호:" + pwd);
                System.out.println("이메일:" + email);
                System.out.println("전화번호:" + phone);
                System.out.println("가입일:" + regdate);
            }
        }catch(ClassNotFoundException ce){
            System.out.println(ce.getMessage());
        }catch(SQLException se){
            System.out.println(se.getMessage());
        }finally{
            try{
                if(rs!=null) rs.close();
                if(stmt!=null) stmt.close();
                if(con!=null) con.close();
            }catch(SQLException se){
                System.out.println(se.getMessage());
            }
        }
    }
}
public class Test03 {
    public static void main(String[] args) {
        new MyJdbc03();
    }
}

 

+ Recent posts