import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Ex_update {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
Scanner sc = new Scanner(System.in);
// 사용자에게 수정하고 싶은 내용 확인하기
System.out.println("===회원 정보 수정===");
System.out.print("아이디 입력>>");
String id = sc.next();
System.out.print("[1]pw [2]name [3]age >>");
int choice = sc.nextInt();
int data =0;
String data2= "";
System.out.print("수정될 데이터 입력");
if(choice ==3) {
data = sc.nextInt();
}else {
data2 = sc.next();
}
String sql ="";
// 선택 메뉴에 따른 sql문 작성
if(choice==1) {
sql = "update members set pw = ? where id = ?";
}
else if(choice ==2) {
sql = "update memebers set name = ? where id =?";
}
else if(choice ==3) {
sql = "update memebers set age = ? where id =?";
}
//2. 데이터베이스 연결
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user_id = "hr";
String user_pw = "hr";
conn = DriverManager.getConnection(url, user_id, user_pw);
// String sql = "update members set pw = '1125' where id = 'cyj'";
psmt = conn.prepareStatement(sql);
if(choice ==3) {
psmt.setInt(1,data);
psmt.setString(2,id);
}else {
psmt.setString(1, data2);
psmt.setString(2, id);
}
//?에 대한 setting 진행하기
int cnt =psmt.executeUpdate();
if(cnt>0) {
System.out.println("수정 완료!");
}else {
System.out.println("수정 실패!");
}
sql= "SELECT * from members where id = ?" ;
//해당 id의 수정된 내용을 보여주는 sql문 작성
psmt = conn.prepareStatement(sql);
psmt.setString(1, id);
rs = psmt.executeQuery(sql);
while(rs.next()) {
String id2 = rs.getString(1);
String pw2 = rs.getString(2);
String name = rs.getString(3);
int age = rs.getInt(4);
System.out.println(id + " " + pw2 + " " + name + " " +age);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("동적오류");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("연결오류");
}
finally {
try {
if(psmt != null) {
psmt.close();}
if(conn !=null) {
conn.close();
}
if(rs !=null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.util.Scanner;
//
//public class Ex_select {
//
// public static void main(String[] args) {
//
// Scanner sc = new Scanner(System.in);
//
// Connection conn = null;
// PreparedStatement psmt = null;
// ResultSet rs = null;
//
// try {// 1. 드라이버 동적로딩 //Oracle클래스를 가지고 오겠다.
// Class.forName("oracle.jdbc.driver.OracleDriver");
//
// // 변수사용이유 내용이길어지고 한번에 다보기 어렵기 때문에
// String url = "jdbc:oracle:thin:@localhost:1521:xe";
// String user_id = "hr";
// String user_pw = "hr";
// // 2. Connection 객체 생성 -> 데이터베이스 연결
// // 데이터베이스에 접근하기 위한 3가지 정보를 담아준다.
// // 문법상에 문제 없지만 연결하면서 오류가 있기때문에 try-catch문
// conn = DriverManager.getConnection(url, user_id, user_pw);
//
// // 어디서 오류나는지 알기위해서 작성
// if (conn != null) {
// System.out.println("연결성공");
// } else {
// System.out.println("연결실패");
// }
// // 3. 사용자의 id,pw 입력받기 -> Scanner 사용
// System.out.println("사용자 id: ");
// String id = sc.next();
// System.out.println("사용자 pw: ");
// String pw = sc.next();
// // 4. 입력된 id, pw와 같은 사용자의 id, pw, name, age 검색(Select)
//// -sql문 작성 후 전송/실행
// String sql = "select * from members where id = ? and pw = ?";
//
// psmt = conn.prepareStatement(sql);
//
// psmt.setString(1, id);
// psmt.setString(2, pw);
//
// //sql문의 조회검색을 실행해주세요
// psmt.executeQuery();//조회/검색(수행 전후에 테이블 값의 변화가 없는 것)
// //esecuteQuery를 쓰면 자동적으로 Resultset쓴다.
//
// // 5. 검색된 내용 console 출력->ResultSet-=>rs.next()
// rs = psmt.executeQuery();
// // ResultSet은 결과값이 표와 같은 형태로 출력해주세요
//
// //select 결과의 행이 몇가지가 나올지 모르므로 반복문을 사용한다.
// while(rs.next()) {//한 행에 내용을 가지고 오고 그 이후에 찾아오는 값이 없을때까지 반복
// String id2 = rs.getString(1);//1번에 있는String형태를 가지고 오겠습니다.
// String pw2 = rs.getString(2);
// String name =rs.getString(3);
// int age = rs.getInt(4);
//
// //출력을 위한 문장
// System.out.println(id2+"\t"+pw2+"\t"+name+"\t"+age);
//
// }
//
// // 실행하면서 발생되는 오류는 catch문을 통해 잡는다.
// } catch (ClassNotFoundException e) {
// System.out.println("동적로딩오류");
// e.printStackTrace();
// } catch (SQLException e) {
// System.out.println("SQL오류");
// e.printStackTrace();
// }
// // 6. 사용된 객체 닫아주기->finally-무조건 한 번은 실행해주세요
// finally {
// if(rs != null) {
// try {
// if(rs != null) {
// rs.close();}
// if(psmt != null) {
// psmt.close();
// }if(conn != null) {
// conn.close();
// }
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
//
//
//
// }
//
//
//
//}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Ex_insert {
public static void main(String[] args) {
// 1. 동적로딩 (드라이버 로딩)
PreparedStatement psmt = null;
Connection conn = null;
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user_id = "hr";
String user_pw = "hr";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
// 이단계 임폴트작업 필수
conn = DriverManager.getConnection(url, user_id, user_pw);
// 객체의 기본값은 null값이다.
if (conn != null) {
System.out.println("연결성공!");
} else {
System.out.println("연결 실패!");
}
// 사용자에게 입력내용 전달받기
Scanner sc = new Scanner(System.in);
System.out.print("아이디 : ");
String id = sc.next();
System.out.print("비밀번호 : ");
String pw = sc.next();
System.out.print("이름 : ");
String name = sc.next();
System.out.print("나이 : ");
int age = sc.nextInt();
// 3. sql문 전송단계
// String sql = "insert into MEMBERS values('test', '1111','테스트', 20)";
String sql = "insert into MEMBERS values(?, ?, ?, ?)";
psmt = conn.prepareStatement(sql);
// sql문애 들어가는 값세팅하기
psmt.setString(1, id);
psmt.setString(2, pw);
psmt.setString(3, name);
psmt.setInt(4, age);
// PreparedStatement의 사용함수
// 1. executeUpdate() //삽입 삭제 수정(이후 테이블의 값이 바뀌는것)
// 2. executeQuery() // 조회/ 검색(수행전후에 테이블 값의 변화가 없는것)
int cnt = psmt.executeUpdate();
if (cnt > 0) {
System.out.println("정보추가 성공");
} else {
System.out.println("정보추가 실패");
}
} catch (ClassNotFoundException e) {
System.out.println("동적로딩 오류!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("sql오류");
e.printStackTrace();
}
// catch문이 끝난 이후 연결 종료
// 에러가 나던 나지 않던 무조건 실행하기 위해 finally
finally {
try
{
if (psmt != null) {
psmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Ex_delete {
public static void main(String[] args) {
//아이디와 비밀번호를 입력하면 해당 내용 테이블로 부터 삭제하기
//1. 동적로딩
Connection conn = null;
ResultSet rs = null;
PreparedStatement psmt = null;
Scanner sc = new Scanner(System.in);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user_id = "hr";
String user_pass = "hr";
System.out.println("DB정상연결");
try {
conn = DriverManager.getConnection(url, user_id, user_pass);
System.out.println("계정접속 성공");
} catch (SQLException e) {
System.out.println("계정접속 실패");
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("DB연결실패");
e.printStackTrace();
}
//3. sql 문 작성
System.out.print("아이디 입력 >>");
String id = sc.next();
System.out.print("비밀번호 입력 >>");
String pw = sc.next();
String sql = "delete from members where id =? and pw =?";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, id);
psmt.setString(2, pw);
int cnt = psmt.executeUpdate();
if(cnt> 0) {
System.out.println("삭제 성공");
}else {
System.out.println("삭제 실패");
}
System.out.println("쿼리 성공");
} catch (SQLException e) {
System.out.println("쿼리실패");
e.printStackTrace();
}
finally {
try {
if(psmt !=null) {
psmt.close();}
if(conn !=null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Ex_01 {
public static void main(String[] args) {
//제이디비씨연결순서
//선행작업 ojdbc.jar추가
//1.JDBC 동적로딩!
//Class.forName()
//클래스 자체 로딩
//컴퓨터의 오류
//컴파일 오류 : 문법적인 오류
//런타임 오류 : 문법상으로는 문제가 없지만, 실제 동작시 오류를 포함하는것
try {//무조건 실행 자체를 해줌 (한번무조건)
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.데이터베이스 연결하기 ->Connection객체를 통하여 연결;
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user_id = "hr";
String user_pw = "hr";
//import java sql
Connection conn = DriverManager.getConnection(url, user_id, user_pw);
if(conn !=null) {
System.out.println("연결 성공");
}else {
System.out.println("연결 실패 ..");
}
//3.sql 작성 -> PrepareStatement()
String sql = "select * from employees where last_name = 'King'";
PreparedStatement psmt = conn.prepareStatement(sql);
//실제 sql실행하는 명령진행
//executeQuery는 원본테이블에 데이터를 변경하지 않는다 - > select
//but executeUpdate() : 원본테이블에 수정이 일어나는 경우 - insert, delete
ResultSet rs = psmt.executeQuery();
while(rs.next()) {
String id = rs.getString(1);
String first_name = rs.getString(2);
String last_name = rs.getString(3);
System.out.println(id);
System.out.println(first_name);
System.out.println(last_name);
}
//연결종료 마지막에 열린 객체부터 역순으로 닫아준다.
//rs - psmt -conn
if(rs !=null) {
rs.close();
}if(psmt !=null) {
psmt.close();
}if(conn !=null) {
conn.close();
}
} catch (ClassNotFoundException e) {
//jdbc 동적로딩을 위한 경로가 맞지 않을 경우 발생하는 오류
//오류나는 부분들을 예외처리 해야하는 영역
// TODO Auto-generated catch block
System.out.println("동적오류");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("데이터 베이스 오류");
//sql 에 해당하는 영역에 대한 오류
e.printStackTrace();
}
}
}