[WHERE] 문제1) 이름에 '나' 문자가 있는 행들을 조회하시오
package jdbc0625;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test04_SelectLike {
public static void main(String[] args) {
String url ="jdbc:oracle:thin:@localhost:1521:xe"; //본인 ip, port listener 1521, xe 무료배포용
String user ="java0514";
String password="1234";
String driver ="oracle.jdbc.driver.OracleDriver"; //ojdbc6.jar
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
Class.forName(driver);
con= DriverManager.getConnection(url, user, password); //get이기때문, 리턴형이 있다.
System.out.println("오라클 DB 서버 연결 성공!");
//문) 이름에 '나' 문자가 있는 행들을 조회하시오
String col ="uname";
String word="나";
//-> " WHERE uname LIKE '%나%' "
/*
String where="";
where+=" WHERE " + col + " LIKE '%" + word + "%' ";
*/
//where stringbuilder를 쓴 이유는 sql문에 직접 입력했을 때, 변수처리? 와 %문자가 겹쳐 인식을 못해서 눈속임을 써서 where변수를 따로 만들어준것
StringBuilder where=new StringBuilder();
where.append(" WHERE ");
where.append(col);
where.append(" LIKE '%");
where.append(word);
where.append("%' ");
//System.out.println(where.toString());
StringBuilder sql=new StringBuilder();
sql.append(" SELECT sno,uname,kor,eng,mat,aver,addr,wdate ");
sql.append(" FROM sungjuk ");
sql.append(where);
sql.append(" ORDER BY uname ");
pstmt=con.prepareStatement(sql.toString());
rs=pstmt.executeQuery();
if(rs.next()){ //cursor가 존재하는지?
do{
System.out.print(rs.getInt("sno") + " ");
System.out.print(rs.getString("uname") + " ");
System.out.print(rs.getInt("kor") + " ");
System.out.print(rs.getInt("eng") + " ");
System.out.print(rs.getInt("mat") + " ");
System.out.print(rs.getInt("aver") + " ");
System.out.print(rs.getString("addr") + " ");
System.out.print(rs.getString("wdate").substring(0, 10) + " ");
System.out.println();
}while(rs.next());
}else{
System.out.println("자료없음!!");
}//if end
}catch(Exception e){
System.out.println("실패!!"+e);
}finally{
try {
if(rs!=null) {rs.close();}
}catch (Exception e) {}
try {
if(pstmt!=null) {pstmt.close();}
}catch (Exception e) {}
try {
if(con!=null) {con.close();}
}catch (Exception e) {}
}//try end
}//main() end
}//class end
출력결과
분석->
where stringbuilder를 쓴 이유는 sql문에 직접 입력했을 때,
변수처리? 와 %문자가 겹쳐 인식을 못해서 눈속임을 써서 where변수를 따로 만들어준것이다.
sql문에 바로 들어갈 경우 '나' 글자를 찾을 때 쓰는 문구는 %나%인데, 변수처리를 해주면 %?%이 된다.
이때 sql문에서 에러가 나므로 where 변수를 따로 만들어주어 sql문에 입력해준다.
[WHERE] 문제2) 제주에 살면서 이름에 '나'문자가 있는 행의 국영수 평균을 반올림해서소수점 둘째짜리까지 구한후
국영수 평균값을 출력하시오
package jdbc0625;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test05_SelectSearch {
public static void main(String[] args) {
String url ="jdbc:oracle:thin:@localhost:1521:xe"; //본인 ip, port listener 1521, xe 무료배포용
String user ="java0514";
String password="1234";
String driver ="oracle.jdbc.driver.OracleDriver"; //ojdbc6.jar
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
Class.forName(driver);
con= DriverManager.getConnection(url, user, password); //get이기때문, 리턴형이 있다.
System.out.println("오라클 DB 서버 연결 성공!");
//문)제주에 살면서 이름에 '나'문자가 있는 행의 국영수 평균을 반올림해서소수점 둘째짜리까지 구한후
// 국영수 평균값을 출력하시오
String addr="Jeju";
String col ="uname";
String word="나";
String where="";
where+=" WHERE " + col + " LIKE '%" + word + "%' ";
where+=" AND addr='" + addr + "'";
StringBuilder sql=new StringBuilder();
sql.append(" SELECT ROUND(avg(kor),2) AS avg_kor, ");
sql.append(" ROUND(avg(eng),2) AS avg_eng, ");
sql.append(" ROUND(avg(mat),2) AS avg_mat ");
sql.append(" FROM sungjuk ");
sql.append(where);
pstmt=con.prepareStatement(sql.toString());
rs=pstmt.executeQuery();
if(rs.next()){ //cursor가 존재하는지?
System.out.println("국어 영어 수학");
System.out.print(rs.getDouble("avg_kor")+" ");
System.out.print(rs.getDouble("avg_eng")+" ");
System.out.print(rs.getDouble("avg_mat")+" ");
}else{
System.out.println("자료없음!!");
}//if end
}catch(Exception e){
System.out.println("실패!!"+e);
}finally{
try {
if(rs!=null) {rs.close();}
}catch (Exception e) {}
try {
if(pstmt!=null) {pstmt.close();}
}catch (Exception e) {}
try {
if(con!=null) {con.close();}
}catch (Exception e) {}
}//try end
}//main() end
}//class end
출력결과
[UPDATE] 문제3 ) 행수정
package jdbc0625;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test07_UpdateTest {
public static void main(String[] args) {
String url ="jdbc:oracle:thin:@172.16.83.16:1521:xe"; //본인 ip, port listener 1521, xe 무료배포용
String user ="java0514";
String password="1234";
String driver ="oracle.jdbc.driver.OracleDriver"; //ojdbc6.jar
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
Class.forName(driver);
con= DriverManager.getConnection(url, user, password); //get이기때문, 리턴형이 있다.
System.out.println("오라클 DB 서버 연결 성공!");
//행수정
String addr="서울";
StringBuilder sql=new StringBuilder();
sql.append(" UPDATE sungjuk ");
sql.append(" SET addr=? ");
sql.append(" WHERE addr='Seoul' ");
pstmt=con.prepareStatement(sql.toString());
pstmt.setString(1, addr);
int result=pstmt.executeUpdate();
if(result==0){
System.out.println("행 수정 실패!");
}else{
System.out.println("행 수정 성공~");
}//if end
}catch(Exception e){
System.out.println("실패!"+e);
}//try end
}//main() end
}//class end
출력결과
분석 -> 변수가 있을 시엔, 변수처리는 ?로 해주고, 변수에 대한 set처리도 해주어야 한다.
[DELETE] 문제4) sno가 1~3인 행을 삭제
package jdbc0625;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test8_DeleteTest {
public static void main(String[] args) {
String url ="jdbc:oracle:thin:@localhost:1521:xe";
String user ="java0514";
String password="1234";
String driver ="oracle.jdbc.driver.OracleDriver";
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
Class.forName(driver);
con=DriverManager.getConnection(url, user, password);
System.out.println("오라클 DB 서버 연결 성공!!");
// 행 삭제 연습
// 문제) sno가 1~3인 행을 삭제
int start=1;
int end=3;
StringBuilder sql=new StringBuilder();
sql.append(" DELETE FROM sungjuk ");
sql.append(" WHERE sno between ? and ? ");
pstmt=con.prepareStatement(sql.toString());
pstmt.setInt(1, start);
pstmt.setInt(2, end);
int result=pstmt.executeUpdate();
if(result==0){
System.out.println("sno 수정 실패!");
}else{
System.out.println("sno 수정 성공~");
}//if end
}catch(Exception e){
System.out.println("실패!"+e);
}finally{
//자원반납(순서주의~!)
try{
if(pstmt!=null){pstmt.close();}
}catch(Exception e){}
try{
if(con!=null){con.close();}
}catch(Exception e){}
}//try end
}//main() end
}//class end
출력결과
'공부 > 응용 SW' 카테고리의 다른 글
6월27일 - MySQL2 자바에 연결하기 / 서브쿼리 / MongoDB (0) | 2019.06.27 |
---|---|
6월26일 - MySQL1 설치하기 (0) | 2019.06.26 |
6월25일 - 오라클 SQL1 (0) | 2019.06.25 |
6월24일 - SW활용 (0) | 2019.06.24 |
6월21일 - SW활용 JDBC : java에 DB연결하기 (0) | 2019.06.21 |