ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [7주][2일][3~4th] JAVA: JDBC 용어 정리, insert/update/delete/select
    N스크린하이브리드앱과정/JAVA 2013. 8. 27. 14:00

    ★ 용어 정리

    데이터베이스 만들기

    create database study;


    데이터베이스 바로 선택하기

    mysql -u root -p1234 <DB명>

    mysql -u root -p1234 study


    비밀번호 바꾸기

    use mysql; //mysql 접속한 상태에서


    1. update user set password=password('123456') where user='root';

     - 설정 적용 : flush privileges;

    2. CMD 창에서 

       mysqladmin -u root -p password 1234



    계정 권한 변경

    grant <권한> on [DB명].[테이블명] to '계정명@localhost(or %)' identified by '패스워드';


     - 권한 : select, insert, delete, update (모든 권한: all privileges)

     - localhost : 로컬 접속만 허용, % : 모든 접속(외부 원격) 허용

     - 권한 부여 후 반드시 flush privileges; 입력(설정 적용하는거!)


    테이블 만들기

    create table member(

    idx int primary key,

    name varchar(20),

    gender varchar(4),

    age varchar(4),

    jumin varchar(20)

    );


    insert into member values(3,'김태희','여자','30');

     -> 원래 5갠데 4개만 적어줘서 에러남!


    insert into member(idx,name,gender,age) values(3,'김태희','여자','30');

     -> 요렇게 해줘야 함


    UPDATE 구문 사용 : 이름이 '김태희'인 사람의 주민등록번호 222222-2222222로 수정

    update set jumin='222222-2222222' where name='김태희'


    DELETE 구문 사용 : 나이가 25 이상이고 성별이 남자인 회원을 삭제

    delete from member where age>=25 and gender='남자'


    member 테이블의 자료형을 변경하기

    alter table [테이블명] CHANGE (column) [기존 필드명] [바꿀 필드명] [바꿀 자료형]

    alter table [테이블명] MODIFY (column) [필드명] [바꿀 자료형]

    alter table member CHANGE column age age int;

    alter table member MODIFY column age int;


    ☆ 실습

    1. Statement 사용하기

    (1) JDBC_Connect1

    public class JDBC_Connect1 {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    try {

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }

    }

    }


    (2) JDBC_Connect2

    public class JDBC_Connect2 {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    // 2단계  - DB 연결

    // jdbc:<DB종류>://DB주소:포트/DB명

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    Connection con = null; // DB연결 객체 선언

    try {

    // 1단계

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    //2단계

    con = DriverManager.getConnection(url, user, password);

    // DB와의 연결을 위한 Connection객체 생성

    // getConnection()은 DB연결에 성공하면

    // 내부적으로 Connection 객체 생성 후 리턴

    // 인스턴스 변수 con에 저장

    System.out.println("DB 연결 성공!");

    con.close(); // DB연결 해제

    } catch (SQLException e) {

    System.out.println("드라이버 연결 실패!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }

    }

    }


    (3) JDBC_Connect3_insert

    public class JDBC_Connect3_Insert {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    // 2단계  - DB 연결

    // jdbc:<DB종류>://DB주소:포트/DB명

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    // 3단계 - Statement 객체 생성

    // 4단계 - SQL문장 실행결과 처리

    Connection con = null; // DB연결 객체 선언

    Statement stmt = null; // DB에 SQL문장 전달 역할

    String sql= null;

    try {

    // 1단계

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    //2단계

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공!");

    //3단계

    stmt = con.createStatement();

    //4단계

    sql = "insert into member values(2,'김길동','남자','30','333333-1111111');";

    // Statement객체의 executeUpdate() 메서드 사용

    stmt.executeUpdate(sql);

    System.out.println("행 추가 성공!");

    //insert, update, delete는 리턴이 필요없다

    //select는 리턴이 필요하다.

    } catch (SQLException e) {

    System.out.println("드라이버 연결 실패!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(stmt !=null)try {stmt.close();} catch (SQLException e) {}

    }

    }

    }


    (4) JDBC_Connect3_update

    public class JDBC_Connect3_Update {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    // 2단계  - DB 연결

    // jdbc:<DB종류>://DB주소:포트/DB명

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    // 3단계 - Statement 객체 생성

    // 4단계 - SQL문장 실행결과 처리

    Connection con = null; // DB연결 객체 선언

    Statement stmt = null; // DB에 SQL문장 전달 역할

    String sql= null;

    try {

    // 1단계

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    //2단계

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공!");

    //3단계

    stmt = con.createStatement();

    //4단계

    sql = "update member set jumin='222222-2222222' where name='김태희';";

    // Statement객체의 executeUpdate() 메서드 사용

    stmt.executeUpdate(sql);

    System.out.println("행 추가 성공!");

    //insert, update, delete는 리턴이 필요없다

    //select는 리턴이 필요하다.

    } catch (SQLException e) {

    System.out.println("드라이버 연결 실패!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(stmt !=null)try {stmt.close();} catch (SQLException e) {}

    }

    }

    }


    (5) JDBC_Connect3_delete

    public class JDBC_Connect3_Delete {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    // 2단계  - DB 연결

    // jdbc:<DB종류>://DB주소:포트/DB명

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    // 3단계 - Statement 객체 생성

    // 4단계 - SQL문장 실행결과 처리

    Connection con = null; // DB연결 객체 선언

    Statement stmt = null; // DB에 SQL문장 전달 역할

    String sql= null;

    try {

    // 1단계

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    //2단계

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공!");

    //3단계

    stmt = con.createStatement();

    //4단계

    sql = "delete from member where age>=25 and gender='남자';";

    // Statement객체의 executeUpdate() 메서드 사용

    stmt.executeUpdate(sql);

    System.out.println("행 추가 성공!");

    //insert, update, delete는 리턴이 필요없다

    //select는 리턴이 필요하다.

    } catch (SQLException e) {

    System.out.println("드라이버 연결 실패이거나 SQL 구문 오류!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(stmt !=null)try {stmt.close();} catch (SQLException e) {}

    }

    }

    }


    (6) JDBC_Connect3_select

    public class JDBC_Connect3_Select {

    public static void main(String[] args) {

    // 1단계 - JDBC 드라이버 로드

    String driver = "com.mysql.jdbc.Driver";

    // 2단계  - DB 연결

    // jdbc:<DB종류>://DB주소:포트/DB명

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    // 3단계 - Statement 객체 생성

    // 4단계 - SQL문장 실행결과 처리

    Connection con = null; // DB연결 객체 선언

    Statement stmt = null; // DB에 SQL문장 전달 역할

    String sql= null;

    ResultSet rs = null;

    try {

    // 1단계

    // java.lang.Class 클래스의

    // 정적 메서드인 forName으로

    // Driver 클래스 로드

    Class.forName(driver); // Driver 클래스 로드

    System.out.println("드라이버 연결 성공!");

    //2단계

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공!");

    //3단계

    stmt = con.createStatement();

    //4단계

    //쿼리문 작성

    sql = "select *from member;";

    // Statement객체의 executeUpdate() 메서드 사용

    // SELECT 구문의 경우 리턴형이 있는

    // executeQuery() 사용

    // 결과값은 ResultSet타입인 rs에 저장

    rs = stmt.executeQuery(sql);

    // SELECT 구문의 결과값은

    // 여러개의 row, column으로 저장

    while(rs.next()){

    // 커서가 rs(테이블) 1행의 위에 위치

    // DB에서 값을 가져올 때 getXXX()사용

    // 여기서 XXX는 자료형.

    int dbidx = rs.getInt(1);

    String dbname = rs.getString(2);

    String dbgender = rs.getString(3);

    int dbage = rs.getInt(4);

    String jumin = rs.getString(5);

    System.out.println(dbidx +" "+dbname+" "+dbgender+" "+dbage+" "+jumin);

    }

    //insert, update, delete는 리턴이 필요없다

    //select는 리턴이 필요하다.

    } catch (SQLException e) {

    System.out.println("드라이버 연결 실패이거나 SQL 구문 오류!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 연결 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(stmt !=null)try {stmt.close();} catch (SQLException e) {}

    if(rs !=null)try {rs.close();} catch (SQLException e) {}

    }

    }

    }



    2. PreparedStatement 사용하기

     - Statement와 차이점 : insert...등의 4가지 기능을 메서드를 사용해서 한 파일에 구현할 수 있다.

                                    즉, sql문을 명시적으로 지정해줘야 하는 statement에 비해 ?를 사용하여 값을

       넣어줄 수 있다는 장점이 있다.


    (1) JDBC_Connect4_PreparedStatement

    public class JDBC_Connect4_PreparedStatement {

    public static void main(String[] args) {

    // insert();

    // delete();

    // update();

    select();

    }

    static void insert(){

    // 1단계 : JDBC 드라이버 로드

    // 2단계 : DB 연결

    // 3단계 : PreparedStatement 객체 생성

    // 4단계 : SQL문 실행 후 결과 처리

    String driver = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    Connection con = null;

    PreparedStatement pstmt = null;

    String sql = null;

    // 외부로부터 입력할 자료를 받아온다고 가정

    int idx = 4;

    String name = "고길동";

    String gender = "남";

    int age = 40;

    String jumin = "555555-5555555";

    try {

    // 1단계 : JDBC 드라이버 로드

    Class.forName(driver);

    System.out.println("드라이버 연결 성공!");

    // 2단계 : DB 연결

    con = DriverManager.getConnection(url, user, password);

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

    // 3단계 : PreparedStatement 객체 생성

    // 매개변수로 사용되는 컬럼은 ?로 지정

    // ?로 지정된 컬럼은 변수로 처리 가능

    // setXXX() 사용하여 값 전달(XXX : 자료형)

    sql = "insert into member values(?,?,?,?,?);";

    pstmt = con.prepareStatement(sql);

    System.out.println("pstmt성공");

    pstmt.setInt(1, idx);

    pstmt.setString(2, name);

    pstmt.setString(3, gender);

    pstmt.setInt(4, age);

    pstmt.setString(5, jumin);

    System.out.println("set성공");

    pstmt.executeUpdate();

    System.out.println("성공");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 로드 실패!");

    } catch (SQLException e) {

    System.out.println("DB접속 실패!");

    }finally{

    if(pstmt != null) try{ pstmt.close(); } catch (Exception e){};

    if(con != null) try{ con.close(); } catch (Exception e){};

    }

    }

    static void delete(){

    // 1단계 : JDBC 드라이버 로드

    // 2단계 : DB 연결

    // 3단계 : PreparedStatement 객체 생성

    // 4단계 : SQL문 실행 후 결과 처리

    String driver = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    Connection con = null;

    PreparedStatement pstmt = null;

    String sql = null;

    int idx = 4;

    String name = "김처니";

    try {

    // 1단계 : JDBC 드라이버 로드

    Class.forName(driver);

    System.out.println("드라이버 연결 성공!");

    // 2단계 : DB 연결

    con = DriverManager.getConnection(url, user, password);

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

    sql = "delete from member where idx=? and name=?;";

    pstmt = con.prepareStatement(sql);

    pstmt.setInt(1, idx);

    pstmt.setString(2, name);

    pstmt.executeUpdate();

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 로드 실패!");

    } catch (SQLException e) {

    System.out.println("DB접속 실패!");

    }finally{

    if(pstmt != null) try{ pstmt.close(); } catch (Exception e){};

    if(con != null) try{ con.close(); } catch (Exception e){};

    }

    }

    static void update(){

    String driver = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    Connection con = null;

    PreparedStatement pstmt = null;

    String sql = null;

    int idx = 1;

    String name = "정길동";

    int age = 20;

    try {

    // 1단계 - 드라이버 로드

    Class.forName(driver);

    // 2단계 - Connection 객체

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공");

    // 3단계 - 쿼리문 작성

    sql = "update member set name=?, age=? where idx=?;";

    pstmt = con.prepareStatement(sql);

    pstmt.setString(1, name);

    pstmt.setInt(2, age);

    pstmt.setInt(3, idx);

    System.out.println("쿼리문 작성 성공!");

    // 4단계 - SQL문 실행 후 결과 처리

    pstmt.executeUpdate(); //select는 executeQuery()!

    System.out.println("수정 성공!");

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 로드 실패!");

    } catch (SQLException e) {

    System.out.println("DB접속 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(pstmt !=null)try {pstmt.close();} catch (SQLException e) {}

    }

    }

    static void select(){

    String driver = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://localhost:3306/study";

    String user = "root";

    String password = "1234";

    Connection con = null;

    PreparedStatement pstmt = null;

    String sql = null;

    ResultSet rs = null; //select 결과값을 저장할 객체

    try {

    // 1단계 - 드라이버 로드

    Class.forName(driver);

    // 2단계 - Connection 객체

    con = DriverManager.getConnection(url, user, password);

    System.out.println("DB 연결 성공");

    // 쿼리문 작성

    sql = "select * from member;";

    // 3단계 - preparedStatement 객체 생성

    pstmt = con.prepareStatement(sql);

    // 4단계 - SQL문 실행 후 결과 처리

    // SELECT 결과를 rs에 저장

    rs = pstmt.executeQuery();

    // 다음 내용(rs.next())이 있을동안 반복

    while(rs.next()){

    int idx = rs.getInt("idx");

    String name = rs.getString("name");

    String gender = rs.getString("gender");

    int age = rs.getInt("age");

    String jumin = rs.getString("jumin");

    System.out.println("========================");

    System.out.println(idx+" "+name+" "+gender+" "+age+" "+jumin);

    System.out.println("성공");

    }

    } catch (ClassNotFoundException e) {

    System.out.println("드라이버 로드 실패!");

    } catch (SQLException e) {

    System.out.println("DB접속 실패!");

    }finally{

    // DB연결 해제

    if(con !=null)try {con.close();} catch (SQLException e) {}

    if(pstmt !=null)try {pstmt.close();} catch (SQLException e) {}

    if(rs !=null)try {rs.close();} catch (SQLException e) {}

    }

    }

    }


Designed by Tistory.