-
어플리케이션 DB접속 (JDBC 라이브러리 이용) (1/19~20)DataBase MySQL 2022. 1. 29. 18:28
Application client로 SQL 쓰기
Eclipse 열고 scrapbook 꺼내기 > connection profile set up하기 > 쿼리 작성해서 실행하기
1/ client에서 Database server 연결하는 방법.
application에서 데이터베이스에 접속할때,
네트워크에서는 약속이 되어있어야한다. 그래야 데이터 보내고 받을 수 있다. > 프로토콜
물리적 거리가 떨어져 있으니까 주소인 url 로 데이터베이스에 접근하고,
DB가 아이디랑 배스워드 받아서 맞으면 들여보내누다.
해당하는 아이디가 할 수 있는 작업들이 등록되어있어서 그 작업만 할 수 있도록 권한을 준다.
접속할때 젤 먼저 드라이버 로딩하고 겟커넥션 받아온다.
public Connection getConnection() { Connection con = null; //mysql에 접속해서 커넥션 객체를 만드는 코드 작성 //url, driver, id, pw 정보 필요 String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/shopdb"; String id = "root"; String pw = "mcys1309"; //driver로딩, 객체를 특이하게 생성함. Class.forName(driver); //url,id,pwd정보로 커넥션 요청 //getConnection method를 여기 메서드를 이용하는게 아니라, DriverManager클래스의 메서드 이용. con = DriverManager.getConnection(url, id, pw); return con; }
**2/ program client에서 database에 저장하기. (preparedstatement 이용)
==삽입하기 INSERT==
public void testInsertV2() throws SQLException { String sql = "insert into emp(emp_name,emp_age,emp_hiredate,dept_code) values(?,?,?,?)"; ConnectionManager cm = new ConnectionManager(); Connection con = cm.getConnection(); //통로생성 PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, "Park"); pstmt.setInt(2, 28); Timestamp stamp = new Timestamp(System.currentTimeMillis()); pstmt.setTimestamp(3, stamp); pstmt.setString(4, "ABCDE"); int affectedCount = pstmt.executeUpdate(); if(affectedCount>0) { System.out.println("삽입완료"); } else { System.out.println("삽입실패"); } cm.closeConnection(con, pstmt, null); } }
==SELECT==
public void testQuery3() { String sql = "select * from usertbl"; //컨넥션 요청 Connection con = new ConnectionManager().getConnection(); //쿼리와 결과가 통과하는 통로 만들기 Statement stmt = null; //결과를 받을 변수 만들기 ResultSet rs = null; stmt = con.createStatement(); //쿼리를 DB로 보내기 //쿼리 결과 받기 rs = stmt.executeQuery(sql); //결과 처리하기 while(rs.next()) { System.out.printf("%s %s %s %n", rs.getString(1),rs.getString(2),rs.getString(3)); } rs.close(); stmt.close(); con.close(); }
**3/ method 활용하기
Collections > sort method (list, comparator)
메서드에 어떤 값이 들어가면 어떤 값이 리턴되는지 아는 게 좋다.
Comparator에 원하는 형식의 데이터를 넣고, 입력된 값을 comparator와 같은 형식으로 return 하는 메서드: sort method
4/ preparedStatement
테이블에 객체저장의 필요성
입력할 데이터만 변경이 될 때
데이터 무결성 확인
5/ connect 프로세스 정리
'DataBase MySQL' 카테고리의 다른 글
mySQL eclipse 셋업, 라이브러리 추가방법 (1/18) (0) 2022.01.18 DataBase, DBMS, mySQL setup (1/14) (0) 2022.01.18