Practice makes perfect

[JAVA] JAVA&DATABASE 연결 본문

빅데이터/JAVA

[JAVA] JAVA&DATABASE 연결

kerpect 2020. 5. 27. 00:51

프로젝트에서 오른쪽 버튼 클릭하여 Built Path -> Add External Archives 선택합니다.

jar파일을 선택합니다.

jar 파일을 선택하면 Referenced Libraries에 생깁니다.

JDBC 드라이버 로딩과 Connection 생성

1.JDBC 드라이버 로딩

  • MySQL의 JDBC Driver Class를 로딩합니다.
  • Class.forName(“driver”)을 이용해서 Driver Class를 로딩하면 객체가 생성되고, DriverManager에 등록됩니다.
  • ex) Class.forName(“com.mysql.jdbc.Driver”)
  • Driver 클래스를 찾지 못할 경우, ClassNotFoundException 예외가 발생 합니다.

2. Connection 생성

  • Connection - 데이터베이스와 연결하는 객체입니다.
  • DriverManager.getConnection(연결문자열, DB_ID, DB_PW) 으로 Connection 객체를 생성합니다.
  • 연결문자열(Connection String) - “jdbc:Driver 종류://IP:포트번호/DB명”
  • ex) jdbc:mysql://localhost:3306/test_db
  • DB_ID : MySQL 아이디
  • DB_PW : MySQL 비밀번호

2.1 DriverManager 클래스

  • DriverManager 클래스는 JDBC 드라이버를 통하여 Connection을 만드는 역할을 합니다.
  • DriverManager는 Class.forName( ) 메소드를 통해서 생성됩니다.
package Eclipse_Db;

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

public class JDBC_Connect {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn= null;
		
		try {
			Class.forName(driver); // java 7 이후 생략 가능.
			conn = DriverManager.getConnection(url, "scott", "tiger");
			
			System.out.println("데이터베이스 연결  성공~~~");
		} catch (ClassNotFoundException | SQLException e) {
			// e.printStackTrace();
			System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
		}finally {
				try {
					if(conn != null) { conn.close(); }
				} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
		}
	}
}

위의 코드를 통해서 DB와 연결이 되었다면 본격적으로 이클립스를 통해서 DB에 데이터를 출력, 저장, 수정, 저장을 해보겠습니다.

위의 데이터를 출력, 저장, 수정, 저장을 위해서는 가장 먼저 해야하는 것은 DataBase에 class만들어서 각각의 특징에 맞는 자료형을 선언해 주는 것입니다.

 

 

 

1) 저장(insert)

public class JDBC_Insert {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn= null;
		Statement stmt = null;
		
		try {
			Class.forName(driver); // java 7 이후 생략 가능.
			conn = DriverManager.getConnection(url, "scott", "tiger");
			
			// System.out.println("데이터베이스 연결  성공~~~");
			
			Scanner input = new Scanner(System.in);
			
			System.out.println("customer 테이블에 값 입력하기...");
			System.out.print("번호 입력 : ");
			int no = input.nextInt();
			
			input.nextLine(); // dummy
			
			System.out.print("이름 입력 : ");
			String name = input.nextLine();
			
			System.out.print("이메일 입력 : ");
			String email = input.nextLine();
			
			System.out.print("전화번호 입력 : ");
			String tel = input.nextLine();
			
			stmt = conn.createStatement();
			
			// insert 쿼리문에 작성.
			String sql = "insert into customer "
					+ "values ("+no+", '"+name+"', '"+email+"', '"+tel+"')";
			
			int result = stmt.executeUpdate(sql);
			
			if(result == 1) {
				System.out.println("데이터 저장 성공");
			}else {
				System.out.println("데이터 저장 실패");
			}
			
		} catch (ClassNotFoundException | SQLException e) {
			// e.printStackTrace();
			System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
		}finally {
				try {
					if(stmt != null) { stmt.close(); }
					if(conn != null) { conn.close(); }
				} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
		}
	}
}

순서

1) database와 연결합니다.

2) scanner를 이용하여 필요한 값을 입력합니다.

3) 입력한 값을 sql문에 넣어서 명령할 것을 정의 하고 int result = stmt.executeUpdate(sql); 를 통해서 DB에 명령해줍니다

4) 저장이 되었으면 "데이터 저장 성공" 저장 되지 않으면 "데이터 저장 실패"가 출력되게 합니다. 

5) 항상 마지막은 컴퓨터의 퍼포먼스를 위해서 사용했던 것들을 finally 에 넣어서 다 꺼주도록 합니다.

 

-sacnner 에 int 값을 입력한 다음 String이 오는 경우에는 항상 더미 코드를 입력하도록 합니다!!

 

 

 

2) 출력(select)

public class JDBC_Select {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn= null;
		Statement stmt = null;
		ResultSet rs = null;
		int no = 0;
		String name = null, email = null, tel = null;
		
		try {
			Class.forName(driver); // java 7 이후 생략 가능.
			conn = DriverManager.getConnection(url, "scott", "tiger");
			
			//System.out.println("데이터베이스 연결  성공~~~");
			
			stmt = conn.createStatement();
			String sql = "select * from customer";
			
			rs = stmt.executeQuery(sql);
			
			System.out.println("번호\t이름\t\t이메일\t\t전화번호");
			System.out.println("-----------------------------------------------");
			
			while(rs.next()) {
				no = rs.getInt("no");
				name = rs.getString("name");
				email = rs.getString("email");
				tel = rs.getString("tel");
				
				System.out.printf("%d\t%s\t%s\t%s\n", 
						                                      no, name, email, tel);
			}
			
		} catch (ClassNotFoundException | SQLException e) {
			// e.printStackTrace();
			System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
		}finally {
				try {
					if(rs != null ) { rs.close(); }
					if(stmt != null) { stmt.close(); }
					if(conn != null) { conn.close(); }
				} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
		}
	}
}

순서

1) database와 연결합니다.

2) sql = "select * from customer"; 를 사용하여 만들어둔 class에 저장되어 있는 값을 가져오도록 합니다.

3) sql문을 통해서 필요한 내용을 정의하고 rs = stmt.executeQuery(sql); 를 통해서 DB에 명령해줍니다.

4) while문을 활용하여 출력되는 값을 변수를 선언하여 변수 안에 넣어줘서 그 값을 출력하게 만듭니다.

5) 저장이 되었으면 "데이터 저장 성공" 저장 되지 않으면 "데이터 저장 실패"가 출력되게 합니다.

6) 항상 마지막은 컴퓨터의 퍼포먼스를 위해서 사용했던 것들을 finally 에 넣어서 다 꺼주도록 합니다.

 

- Resultset이란?

Java에서 사용하는 것은 일단 DB 연결되는 통로를 열고, 통로로 명령을 보내고, 통로로 보낸 명령에 대해서 DB 처리해서 값을 돌려보내주는 식으로 처리 됩니다. execteQuery 명령하면 ResultSet이라는 객체를 돌려줍니다.

 

execteQuery : DB 명령 ( rs = stmt.executeQuery(sql); )

ResultSet : 명령에 대한 반환값. 반환해주는 값은 테이블을 보시면서 해야 이해하시는 것이 좋을것 같습니다.

 

execteQuery("Select * from tableName"); 이라고 보냈다면 tableName 라는 테이블에서 값을 가져올겁니다. 가져온 것이 ResultSet입니다. 간단히 DB 명령을 내리는 것입니다. 그러면 명령에 따라서 디비가 작동하고, 작동한 결과 값을 돌려준다는 말입니다.

 

 

 

3) 수정(Update)

ublic class JDBC_Update {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn= null;
		Statement stmt = null;
		
		try {
			Class.forName(driver); // java 7 이후 생략 가능.
			conn = DriverManager.getConnection(url, "scott", "tiger");
			
			// System.out.println("데이터베이스 연결  성공~~~");
			
			Scanner input = new Scanner(System.in);
			
			System.out.println("customer 테이블에 값 수정하기...");
			System.out.print("수정할 번호 입력 : ");
			int no = input.nextInt();
			
			input.nextLine(); // dummy
			
			System.out.print("변경할 이름 입력 : ");
			String name = input.nextLine();
			
			System.out.print("변경할 이메일 입력 : ");
			String email = input.nextLine();
			
			System.out.print("변경할 전화번호 입력 : ");
			String tel = input.nextLine();
			
			stmt = conn.createStatement();
			
			// update 쿼리문에 작성.
			String sql = "update customer set name = '"+name+
					                                      "', email = '"+email+
					                                      "', tel = '"+tel+
					                                      "' where no = "+no;
			
			int result = stmt.executeUpdate(sql);
			
			if(result == 1) {
				System.out.println("데이터 수정 성공");
			}else {
				System.out.println("데이터 수정 실패");
			}
			
		} catch (ClassNotFoundException | SQLException e) {
			// e.printStackTrace();
			System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
		}finally {
				try {
					if(stmt != null) { stmt.close(); }
					if(conn != null) { conn.close(); }
				} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
		}
	}
}

순서)

1) database를 연결합니다.

2) Scanner을 통해서 변경할 값을 입력 합니다.

3) 수정을 위해서 sql문에 where을 사용해서 조건을 달아줍니다. 저는 no의 값을 입력해서 수정할것이기 때문에

where = no 라고 입력해주었습니다.

4) executeUpdate를 사용하여 DB에게 명령해줍니다.

5) 저장이 되면 "데이터 수정 성공 " 저장되지 않으면 "데이터 수정 실패" 가 입력하도록 합니다.

6) 항상 마지막은 컴퓨터의 퍼포먼스를 위햐서 finally에서 다 종료시켜줍니다.

 

 

 

4)삭제(delete)

public class JDBC_Delete {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn= null;
		Statement stmt = null;
		
		try {
			Class.forName(driver); // java 7 이후 생략 가능.
			conn = DriverManager.getConnection(url, "scott", "tiger");
			
			//System.out.println("데이터베이스 연결  성공~~~");
			
			Scanner input = new Scanner(System.in);
			
			System.out.println("customer 테이블에서 레코드 삭제하기...");
			System.out.print("삭제할 번호 입력 : ");
			int no = input.nextInt();
			
			stmt = conn.createStatement();
			
			String sql = "delete from customer where no = "+no;
			int result = stmt.executeUpdate(sql);
			
			if(result == 1) {
				System.out.println("데이터 삭제 성공");
			}else {
				System.out.println("데이터 삭제 실패");
			}
			
		} catch (ClassNotFoundException | SQLException e) {
			// e.printStackTrace();
			System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
		}finally {
				try {
					if(stmt != null) { stmt.close(); }
					if(conn != null) { conn.close(); }
				} catch (SQLException e) {
					System.out.println(e.getMessage());
				}
		}
	}
}

위의 수정과 같은 방식으로 sql문에서 update를 delete로 고쳐주면 작동하게 됩니다.

 

 

위의 내용들에서 sql문에서 정보드를 숨기고 싶을 떄는 preapareStatement 를 사용하여 sql 따로 입력하도록 만들어줍니다.

String sql = "insert into customer values (?, ?, ?, ?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, no);
			pstmt.setString(2, name);
			pstmt.setString(3, email);
			pstmt.setString(4, tel);

위와 같은 형태로 사용합니다.

ublic class JDBC_Update {
 public static void main(String[] args) {
  String driver = "oracle.jdbc.driver.OracleDriver";
  String url = "jdbc:oracle:thin:@localhost:1521:xe";
  Connection conn= null;
  Statement stmt = null;
  
  try {
   Class.forName(driver); // java 7 이후 생략 가능.
   conn = DriverManager.getConnection(url, "scott", "tiger");
   
   // System.out.println("데이터베이스 연결  성공~~~");
   
   Scanner input = new Scanner(System.in);
   
   System.out.println("customer 테이블에 값 수정하기...");
   System.out.print("수정할 번호 입력 : ");
   int no = input.nextInt();
   
   input.nextLine(); // dummy
   
   System.out.print("변경할 이름 입력 : ");
   String name = input.nextLine();
   
   System.out.print("변경할 이메일 입력 : ");
   String email = input.nextLine();
   
   System.out.print("변경할 전화번호 입력 : ");
   String tel = input.nextLine();
   
   stmt = conn.createStatement();
   
   // update 쿼리문에 작성.
   String sql = "update customer set name = '"+name+
                                           "', email = '"+email+
                                           "', tel = '"+tel+
                                           "' where no = "+no;
   
   int result = stmt.executeUpdate(sql);
   
   if(result == 1) {
    System.out.println("데이터 수정 성공");
   }else {
    System.out.println("데이터 수정 실패");
   }
   
  } catch (ClassNotFoundException | SQLException e) {
   // e.printStackTrace();
   System.out.println("데이터베이스 연결  실패 ㅠㅠㅠ");
  }finally {
    try {
     if(stmt != null) { stmt.close(); }
     if(conn != null) { conn.close(); }
    } catch (SQLException e) {
     System.out.println(e.getMessage());
    }
  }
 }

'빅데이터 > JAVA' 카테고리의 다른 글

[JAVA] JAVA&DATABASE - (DAO, DTO)  (0) 2020.06.06
[JAVA] 이클립스, DB 연동 환경설정  (0) 2020.05.26
[JAVA] SWING (2)  (0) 2020.05.25
[JAVA] SWING(1)  (0) 2020.05.23
[JAVA] 네트워크(NETWORK)  (0) 2020.05.23