[자바기초] mySQL 사용하기 위한 기본문법(Driver load, Connection, Statement)


처음 mySQL을 사용하는 사람이라면 반드시 알아야 할 내용들 ㅎㅎ

물론 나중에는 클래스화 해서 합쳐져야할 내용들이지만 처음에 돌아가는 구조를 보기 위해서 하나하나 익혀야 할 내용들이다.

(당연히 mySQL에 bbsdb라는 DB가 만들어져 있어야 한다)

C:\Program Files\Java\jdk1.8.0_211\jre\lib\ext /개발킷쪽에 추가
C:\Program Files\Java\jre1.8.0_211\lib\ext / 인터넷실행환경에 추가
위에 폴더에 각각 mySQL driver가 설치(복사)가 되어져 있어야 한다.


JDBC_Connect01_driver_load

package com.ljh;

public class JDBC_Connect01_driver_load {
 
 public static void main(String[] args) {
  
  //mySQL전용
  String driver = "com.mysql.jdbc.Driver";
  
  try {
   Class.forName(driver);
   System.out.println("드라이버 로드 성공!");
   
  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());
  }
 }
}




JDBC_Connect02_db_connect

package com.ljh;

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

public class JDBC_Connect02_db_connect {
 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";  //mySQL 전용 드라이버 이름
  String url = "jdbc:mysql://localhost:3306/bbsdb"; //mySQL 서버 전용
  Connection con = null;

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234"); //Connection 객체 반환

   System.out.println("데이터베이스 연결 성공!");

  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("데이터베이스 연결 ERR! : " + e.getMessage());

  } finally {
   try {
    if (con != null) {
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("Connection 자원해제 ERR! : " + e.getMessage());
   }
  }

 }
}




JDBC_Connect03_statement

package com.ljh;

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

public class JDBC_Connect03_statement {

 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  Connection con = null;
  Statement stmt = null;     //쿼리를 실행하기 위해서 반드시 선언해줘야 함;

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234");
   
   stmt = con.createStatement();
   System.out.println("Statement 객체 생성 성공!");

  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());

  } finally {
   try {
    if (stmt != null) {
     stmt.close();
    }
    if (con != null) {
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Delete_Statement

package com.ljh;

import java.io.BufferedReader; // 도스 콘솔 창에서 사용자 입력을 받아들이기 위해 BufferedReader 
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Delete_Statement {

 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  Connection con = null;
  Statement stmt = null;

  String sql;
  String name;
  String no;

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234");
   stmt = con.createStatement();

   // ---JDBC_Delete 변경된 내용-------
   // 테이블에 추가할 내용을 도스 콘솔 창에서 사용자의 입력을 받도록 한다.
   BufferedReader br = new BufferedReader(new InputStreamReader(
     System.in));

   System.out.println(" customer 테이블에서 레코드 삭제하기 .....");
   System.out.print("어떤 분의 내용을 삭제할지 그분의 숫자를 입력하세요: ");
   no = br.readLine(); // 테이블에서 삭제할 name 필드 값을 입력 받음

   // DELETE 쿼리문을 작성
   sql = "DELETE FROM customer WHERE name ='";
   sql += no + "'";

   // Statement 객체의 executeUpdate(sql) 메서드를 이용해
   stmt.executeUpdate(sql); // 데이터베이스 파일에서 레코드 삭제시킴

  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());

  } catch (IOException e) {
   System.out.println("IO ERR! : " + e.getMessage());

  } finally {
   try {
    if (stmt != null) {
     stmt.close();
    }
    if (con != null) {
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Insert_Statement

package com.ljh;

//도스 콘솔 창에서 사용자 입력을 받아들이기 위해 BufferedReader 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Insert_Statement {
 
 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  Connection con = null;
  Statement stmt = null;     //쿼리를 실행하기 위해서 반드시 선언해줘야 함;
  //insert into customer (no, name, email, phone) values (1,"a", "b", "c");
  String sql;

  String name, email, tel, no;

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234");
   stmt = con.createStatement();
   
   // ---JDBC_Insert 추가된 내용-------
   // 테이블에 추가할 내용을 도스 콘솔 창에서 사용자의 입력을 받도록 한다.
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   //줄단위로 읽어내는 메소드
   
   System.out.println(" customer 테이블에 값 입력하기 .....");

   System.out.print(" 번호 입력: ");
   no = br.readLine(); // 테이블에 추가할 no 필드 값을 입력 받음

   System.out.print(" 이름 입력: ");
   name = br.readLine(); // 테이블에 추가할 name 필드 값을 입력 받음
   
   System.out.print(" 이메일 입력: ");
   email = br.readLine(); // 테이블에 추가할 email 필드 값을 입력 받음
   
   System.out.print(" 전화번호 입력: ");
   tel = br.readLine(); // 테이블에 추가할 tel 필드 값을 입력 받음

   // INSERT 쿼리문을 작성
   sql = "INSERT into customer (no, name, email, phone) values ";
   sql += "(" + no + ",'" + name + "','" + email + "','" + tel + "')";

   // Statement 객체의 executeUpdate(sql) 메서드를 이용해
   stmt.executeUpdate(sql); // 데이터베이스 파일에 새로운 값을 추가시킴
   
  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());
   
  }  catch (IOException e) {
   System.out.println("IO ERR! : " + e.getMessage());
   
  } finally {
   try {
    if (stmt != null){
     stmt.close();
    }
    if (con != null){
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Insert2_PreparedStatement

package com.ljh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBC_Insert2_PreparedStatement {

 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  Connection con = null;

  PreparedStatement pstmt = null; // PreparedStatement 객체 변수 pstmt를 선언
  
  int no;
  String name, email, phone, temp; // 데이터베이스에서 얻어온 필드 값 저장할 변수 선언
  
  String sql; // SQL문을 저장할 변수 선언

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234");

   // ---JDBC_Insert2 추가된 내용-------
   // 테이블에 추가할 내용을 도스 콘솔 창에서 사용자의 입력을 받도록 한다.
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   
   System.out.println(" customer 테이블에 값 입력하기 .....");
   System.out.print(" 번호 입력: ");
   temp = br.readLine();
   
   System.out.print(" 이름 입력: ");
   name = br.readLine(); // 테이블에 추가할 name 필드 값을 입력 받음
   
   System.out.print(" 이메일 입력: ");
   email = br.readLine(); // 테이블에 추가할 email 필드 값을 입력 받음
   
   System.out.print(" 전화번호 입력: ");
   phone = br.readLine(); // 테이블에 추가할 phone 필드 값을 입력 받음

   // ? 문자가 포함된 INSERT 문을 작성
   sql = "INSERT INTO customer(no, name, email, phone) values (?,?,?,?)";
 
   
   // PrepareStatement를 객체를 생성
   pstmt = con.prepareStatement(sql);
          //!! 기본적으로 그냥 statement는 sql 처리할때 sql문 불러오지만 prepare은 객채가 만들어질때 sql문 필요함;
   
   no = Integer.parseInt(temp);
   pstmt.setInt(1, no); // 첫 번째 ? 에 사용자로부터 입력받은 번호를 대입
   pstmt.setString(2, name); // 두 번째 ? 에 사용자로부터 입력받은 이름을 대입
   pstmt.setString(3, email); // 세 번째 ? 에 사용자로부터 입력받은 이메일을 대입
   pstmt.setString(4, phone); // 네 번째 ? 에 사용자로부터 입력받은 전화번호를 대입

   // PreparedStatement 객체의 executeUpdate( ) 메서드를 이용해
   pstmt.executeUpdate(); // 데이터베이스 파일에 새로운 값을 추가시킴
         //!! sql을 미리 가지고 있기 때문에 매개변수로 sql이 필요하지 않음;
   
  }catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());
   
  }  catch (IOException e) {
   System.out.println("IO ERR! : " + e.getMessage());
   
  } finally {
   try {
    if (pstmt != null){
     pstmt.close(); // PrepareStatement 객체를 메모리에서 해제
    }
    if (con != null){
     con.close();
    }
     
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }// finally 끝
 }
}




JDBC_Meta

package com.ljh;

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

public class JDBC_Meta {
 
 public static void main(String[] args) {
  
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  String user = "root";
  String pwd = "1234";

  Connection con = null;
  
  
  PreparedStatement pstmt = null; // PreparedStatement 객체 변수 pstmt를 선언
  String sql; // SQL문을 저장할 변수 선언
  ResultSet rs = null;
  //rs가 먼저 있어야됨!;
  
  ResultSetMetaData rsm; // ResultSetMetaData 객체 변수 선언

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, user, pwd);

   sql = "SELECT * FROM customer";
   pstmt = con.prepareStatement(sql);

   rs = pstmt.executeQuery();
   // ResultSet 객체로 getMetaData() 메서드를 호출하여 ResultSetMetaData 객체 생성
   rsm = rs.getMetaData();

   // ResultSetMetaData 의 getColumnCount() 메서드는 컬럼의 개수를 반환한다.
   int cols = rsm.getColumnCount();
   System.out.println("컬럼의 개수 : "+cols);

   // 컬럼 목록 보여주기
   for (int i = 1; i <= cols; i++) {
    // ResultSetMetaData 의 getColumnName( ) 메서드는 해당 위치의 컬럼명을 반환
    System.out.print(rsm.getColumnName(i) + "\t\t");
   }
   
   System.out.println();
   
   // 얻어낸 컬럼 값 보여주기
   while (rs.next()) {
    for (int i = 1; i <= cols; i++){
     System.out.print(rs.getObject(i) + "\t\t");
    }
    System.out.println();
   }

  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());

  } finally {
   
   try { // rs, stmt, con 객체를 close() 메서드를 호출해 해제
    if (rs != null){
     rs.close();
    }
    if (pstmt != null){
     pstmt.close();
    }
    if (con != null){
     con.close();
    }
    
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Select_Statement

package com.ljh;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Select_Statement {
 
 public static void main(String[] args) {
  
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  Connection con = null;
  Statement stmt = null;
  
  // ---JDBC_Select 추가된 내용 -------
  ResultSet rs = null;
  int no = 0;
  
  String name, email, phone; // 데이터베이스에서 얻어온 필드값 저장할 변수 선언
  String sql; // SQL문을 저장할 변수 선언
  
  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, "root", "1234");
   stmt = con.createStatement();
   
   // ---JDBC_Select 추가된 내용 -------
   sql = "SELECT * FROM customer";
   System.out.printf("번호 \t 이름 \t\t 이메일 \t\t 전화번호 \n");
   System.out.printf("-----------------------------------------------------------------\n");
   
   rs = stmt.executeQuery(sql); // 얻어진 레코드를 가져옴
   while (rs.next()) {
                        //    no = rs.getInt("no");
                        //    name = rs.getString("name");
                        //    email = rs.getString("email");
                        //    phone = rs.getString("phone");
                        //    
    //테이블의 인덱스명은 1번부터
    no = rs.getInt(1);
    name = rs.getString(2);
    email = rs.getString(3);
    phone = rs.getString(4);
    
    System.out.printf(" %d \t %s \t %s \t %s\n", no, name, email, phone);
   }
   
  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());
   
  } finally {
   try { // rs, stmt, con 객체를 close() 메서드를 호출해 해제
    if (rs != null){
     rs.close();
    }
    if (stmt != null){
     stmt.close();
    }
    if (con != null){
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Select2_PreparedStatement_Search

package com.ljh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBC_Select2_PreparedStatement_Search {

 public static void main(String[] args) {

  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/bbsdb";
  String user = "root";
  String pwd = "1234";

  Connection con = null;
  PreparedStatement pstmt = null;

  String s_name, s_email, s_phone;
  String sql;

  ResultSet rs = null;

  try {
   Class.forName(driver);
   con = DriverManager.getConnection(url, user, pwd);

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   System.out.println("customer 테이블에서 찾고자하는 사람이름이나 이메일이나 전화번호를 입력하기");
   
   System.out.print(" 이름 입력: ");
   s_name = br.readLine(); // 테이블에서 찾고자하는 사람의 이름을 입력 받음
   
   System.out.print(" 이메일 입력: ");
   s_email = br.readLine(); // 테이블에서 찾고자하는 사람의 이메일을 입력 받음
   
   System.out.print(" 전화번호 입력: ");
   s_phone = br.readLine(); // 테이블에서 찾고자하는 사람의 전화번호를 입력 받음

   // SELECT 쿼리문을 작성
   sql = "SELECT * FROM customer WHERE name LIKE ? AND email LIKE ? AND phone LIKE ? ";
   pstmt = con.prepareStatement(sql);

   if (s_name.equals("")){
    s_name = "%";
   }
   if (s_email.equals("")){
    s_email = "%";
   }
   if (s_phone.equals("")){
    s_phone = "%";
   }

   pstmt.setString(1, s_name);
   pstmt.setString(2, s_email);
   pstmt.setString(3, s_phone);

   // PreparedStatement 객체의 executeQuery( ) 메소드로 데이터 검색
   rs = pstmt.executeQuery();
   System.out.println("\n\n --------- 검색 결과 출력 ---------- ");
   
   while (rs.next()) {
    s_name = rs.getString("name");
    s_email = rs.getString("email");
    s_phone = rs.getString("phone");
    // 컬럼 값을 화면에 출력
    System.out.println(s_name + " \t " + s_email + " \t " + s_phone);
   } // while
               //
               //   rs.close();
               //   pstmt.close();
               //   con.close();
   
  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());

  } catch (IOException e) {
     System.out.println("IO ERR! : " + e.getMessage());
     
  } finally {
   try { // rs, stmt, con 객체를 close() 메서드를 호출해 해제
    if (rs != null) {
     rs.close();
    }
    if (pstmt != null) {
     pstmt.close();
    }
    if (con != null) {
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}




JDBC_Update_Statement

package com.ljh;

import java.io.BufferedReader; // 도스 콘솔 창에서 사용자 입력을 받아들이기 위해 BufferedReader 
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Update_Statement {
 
 public static void main(String[] args) {
  String driver = "com.mysql.jdbc.Driver";  //드라이버 명칭 ㅎ
  String url = "jdbc:mysql://localhost:3306/bbsdb"; //접속주소도 문자열 ㅎ
  Connection con = null;
  Statement stmt = null;     //업데이트 하게되면 받게될 변수

  String sql;
  String name, email, phone;

  try {
   Class.forName(driver);    //드라이버 로딩 해와야함
   con = DriverManager.getConnection(url, "root", "1234");
   stmt = con.createStatement();
   
   // ---JDBC_Insert 추가된 내용-------
   // 테이블에 추가할 내용을 도스 콘솔 창에서 사용자의 입력을 받도록 한다.
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   //바이너리값,,, 스캔이랑 다름;
   
   
   System.out.println(" customer 테이블에 값 갱신하기 .....");
   System.out.print("어떤 분의 내용을 갱신할지 그분의 이름을 입력하세요: ");
   name = br.readLine(); // 테이블에 추가할 name 필드 값을 입력 받음
   
   System.out.print("변경할 이메일 입력: ");
   email = br.readLine(); // 테이블에 추가할 email 필드 값을 입력 받음
   
   System.out.print("변경할 전화번호 입력: ");
   phone = br.readLine(); // 테이블에 추가할 tel 필드 값을 입력 받음

   // INSERT 쿼리문을 작성
   sql = "UPDATE customer SET email='" + email;
   sql += "' , phone='" + phone + "' WHERE name ='";
   sql += name + "'";

   // Statement 객체의 executeUpdate(sql) 메서드를 이용해
   stmt.executeUpdate(sql); // 데이터베이스 파일의 내용을 변경시킴
   
  } catch (ClassNotFoundException e) {
   System.out.println("드라이버 ERR! : " + e.getMessage());

  } catch (SQLException e) {
   System.out.println("SQL ERR! : " + e.getMessage());
  
  }  catch (IOException e) {
   System.out.println("IO ERR! : " + e.getMessage());
   
  } finally {
   try {
    if (stmt != null){
     stmt.close();
    }
    if (con != null){
     con.close();
    }
   } catch (SQLException e) {
    System.out.println("자원해제 ERR! : " + e.getMessage());
   }
  }
 }
}

댓글

이 블로그의 인기 게시물

[자바기초] jxl을 이용하여 자바에서 엑셀파일 읽고,쓰기

[자바기초] Vector, Iterator를 이용해서 정수 삽입후 모든 정수 출력 및 합산

[자바기초] HashMap으로 [학생 이름, Student 객체]를 이용하여 저장, 출력