JDBC1

JDBC 기초

JDBC


  1. Java DataBase Connectivity의 약어
  2. 표준 API로 모든 DB와 연동하는 코드가 동일함을 보장
  3. DB연동 표준 API


JDBC 환경셋팅


  1. maven
  1. git & github
  1. 수동으로 사용자가 설정
    • 개발되는 project당 별도로 셋팅
    • properties/Java Build Path/Add Libraries/User Libraries

→ C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar


JDBC 사용법


static{	
	try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
		System.out.println("해당 driver가 없습니다.");
	}
}
//요청시마다 새로운 connection 객체 생성해서 반환하는 메소드
//URL, ID, PW
public static Connection getConnection() throws SQLException {
	String url = "jdbc:oracle:thin:@아이피주소:1521:xe";
	Connection con = DriverManager.getConnection(url, "아이디", "비밀번호");
	return con;
}


// rset의 경우 없어도 되게 하기 위해 인자가 2개인 메소드 추가선언 필요
public static void close (Connection con, Statement stmt, ResultSet rset) {
	try {
		if (rset != null) {
			rset.close();
			rset=null;
		}
		if(stmt != null) {
			stmt.close();
		}
		if(con != null) {
			con.close();
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
}


Connection con = DBUtil.getConnection();
Statement stmt = con.createStatement();

// -----------------------
ResultSet rset = stmt.excuteQuerry("select * from dept");
rset.next() // 다음 읽을 값이 있는지 확인
//컬럼 순서로 데이터 뽑기
System.out.println(rset.getInt(1) + " " +
									rset.getString(2) + " " +
									rset.getString(3));
//컬럼 명으로 데이터 뽑기
System.out.println(rset.getInt("deptno") + " " + 
									rset.getString("dname") + " " + 
									rset.getString("loc"));

// --------------------
pstmt = con.prepareStatement("insert into dept values(?, ?, ?)");
pstmt.setInt(1, newDeptno);
pstmt.setString(2, newDname);
pstmt.setString(3, newLoc);
int result = pstmt.executeUpdate() // 선택된 row 수 반환

//---------------------
pstmt = con.prepareStatement("update dept set loc=? where deptno=?");
pstmt.setString(1, newLoc);
pstmt.setInt(2, Deptno);
int result = pstmt.executeUpdate() // 선택된 row 수 반환

//---------------------
pstmt = con.prepareStatement("delete from dept where dname=?");
pstmt.setString(1, delName);
int result = pstmt.executeUpdate();

DBUtil.close(con, stmt, rset);


Properties를 활용한 sql 구문 저장


# oracle DB info
driver=oracle.jdbc.driver.OracleDriver
url= jdbc:oracle:thin:@아이피:1521:xe
id= ~~~
pw= ~~~
private static Properties pro = new Properties();
private static Properties sqlAll = new Properties();

sqlAll.load(new FileInputStream("sqlAll.properties"));
pro.load(new FileInputStream("dbinfo.properties"));
			
Class.forName(pro.getProperty("driver"));
# warning blank
# dept table crud
dept.All=select * from dept
dept.getDept=select * from dept where deptno=?
dept.insert=into dept values(?, ?, ?)
dept.update=update dept set (loc, dname) = (select ?,? from dual) where deptno = ?
dept.delete=delete from dept where deptno=?
con = DBUtil.getConnection();
stmt = con.createStatement();
rset = stmt.executeQuery(DBUtil.getSqlAll().getProperty("deptAll"));

datas = new ArrayList<>();
datas.add(new DeptDTO(rset.getInt("deptno"), 
											rset.getString("dname"),
											rset.getString("loc")));

Discussion and feedback