# 23. Java 22일차(230914) [국비교육]

brand_mins·2023년 9월 14일

Java

목록 보기
23/47
JDBC 프로그래밍 이어서 실습
이 부분은 꾸준히 계속 보기

1. prepareStatement

  • statement를 업그레이드해서 preparedStatement 만들기 가능
  • preparedStatement는 sql문자열에서 데이터 부분을 ?표를 사용하여 값을 넣음.
1. select
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;

public class JdbcSelect {

	public static void main(String[] args) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url="jdbc:oracle:thin:@localhost:1521:xe";
		String user="c##human";
		String pw="human";
		Connection conn=DriverManager.getConnection(url,user,pw);
		String sql="select * from human";
		System.out.println("sql 에러시 여기서 문자열을 확인:"+sql);
		PreparedStatement ps=conn.prepareStatement(sql);
		ResultSet rs=ps.executeQuery();
		while(rs.next()) {
		String name =rs.getString("name");
		int age=rs.getInt("age");
		double height=rs.getDouble("height");
		LocalDateTime birthday=rs.getTimestamp("birthday").toLocalDateTime();
		System.out.println("name:"+name);
		System.out.println("age:"+age);
		System.out.println("height:"+height);
		System.out.println("birth:"+birthday);
		System.out.println("---------------------------");
		}
		if(rs!=null)rs.close();
		if(ps !=null) ps.close();
		if(conn !=null) conn.close();
	}
}

2. insert
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.time.LocalDateTime;

public class JdbcInsert {
		public static void main(String[] args) throws Exception{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url="jdbc:oracle:thin:@localhost:1521:xe";
			String user="c##human";
			String pw="human";
			Connection conn=DriverManager.getConnection(url,user,pw);
			String sql="insert into human values(?,?,?,?)";
			System.out.println("sql 에러시 여기서 문자열을 확인:"+sql);
			PreparedStatement ps=conn.prepareStatement(sql);
			ps.setString(1, "홍길동");
			ps.setInt(2, 10);
			ps.setDouble(3, 42.2);
			//LocalDateTime >> Timestamp
			//java.time.LocalDateTime 자바에서 시간을 다루는 클래스
			//java.sql.Timestamp 데이터베이스에 넣을때 사용되는 시간 클래스
			ps.setTimestamp(4,Timestamp.valueOf(LocalDateTime.now()));
			int n = ps.executeUpdate();
			System.out.println(n+"개의 로우 변경");
			if(ps !=null) ps.close();
			if(conn !=null) conn.close();


	}

}

3. Delete
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JdbcDelete {

	public static void main(String[] args) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url="jdbc:oracle:thin:@localhost:1521:xe";
		String user="c##human";
		String pw="human";
		Connection conn=DriverManager.getConnection(url,user,pw);
		String sql="delete from human where name=?";
		System.out.println("sql 에러시 여기서 문자열을 확인:"+sql);
		PreparedStatement ps=conn.prepareStatement(sql);
		ps.setString(1, "홍길동");
		int n = ps.executeUpdate();
		System.out.println(n+"개의 로우 변경");
		if(ps !=null) ps.close();
		if(conn !=null) conn.close();

	}

}

4. update
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class JdbcUpdate {

	public static void main(String[] args) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url="jdbc:oracle:thin:@localhost:1521:xe";
		String user="c##human";
		String pw="human";
		Connection conn=DriverManager.getConnection(url,user,pw);
		String sql="update human set age=? where name=?";
		System.out.println("sql 에러시 여기서 문자열을 확인:"+sql);
		PreparedStatement ps=conn.prepareStatement(sql);
		ps.setInt(1, 13);
		ps.setString(2, "홍길동");
		int n = ps.executeUpdate();
		System.out.println(n+"개의 로우 변경");
		if(ps !=null) ps.close();
		if(conn !=null) conn.close();
	}
}

2. DBConn과 userInput

(1) DBConn 클래스

  • 복잡한 JDBC 사용방법을 쉽게 구현
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConn {
	// 생성자를 private로 설정하여 외부에서 객체 생성하지 못하도록 함.
	private DBConn() {}
	// DB연결을 위한 Connection 객체를 static으로 선언하여 클래스 변수로 사용
	private static Connection dbConn = null;
	// 쿼리 실행을 위한 Statement 객체를 static으로 선언하여 클래스 변수로 사용
	private static Statement st = null;
	// 쿼리 실행 결과를 저장하기 위한 Resultset 객체를 static으로 선언하여 클래스 변수로 사용
	private static ResultSet rs = null;
	// DB연결을 위한 메소드. 싱글폰 패턴을 사용하여 이미 연결되어 있는 경우 연결 객체 반환. 연결x: 새로운 연결객체 사용
	public static Connection getInstance() {
		if(dbConn == null) {
			try {
				Class.forName("oracle.jdbc.driver.OracleDriver");
				String url = "jdbc:oracle:thin:@localhost:1521:xe";
				String id = "c##human";
				String pw = "human";
				dbConn = DriverManager.getConnection(url,id,pw);
				System.out.println("DBConnection...");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return dbConn;
	}
	// DB연결을 종료하는 메소드
	public static void dbClose() {
		try {
			if(rs != null) rs.close();
			if(st != null) st.close();
			if(dbConn != null) dbConn.close();
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			rs = null; st = null; dbConn = null;
		}
	}
	
	// insert, update, delete 등 쿼리 실행결과를 반환하지 않는 쿼리문 실행
	// 쿼리문을 매개변수로 받아 Statement 객체를 생성하여 쿼리문 실행
	public static int statementUpdate(String sql) {
		DBConn.getInstance();
		int rValue = -1;
		if(dbConn != null) {
			try {
				if(st == null) st = dbConn.createStatement();
				rValue = st.executeUpdate(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("not connected....");
		}
		return rValue;
		
	}
	// select 등 쿼리 실행결과를 반환하는 쿼리문을 실행하는 메소드
	// 자바에서 오라클 db 사용가능
	public static ResultSet statementQuery(String sql) {
		DBConn.getInstance();
		if(DBConn.dbConn != null) {
			try {
				if(st == null) st = dbConn.createStatement();
				rs = st.executeQuery(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("not connected...");
		}
		return rs;
	}
}

2. 메인메소드
- while문을 사용하여 모든 행 순회
- getString(), getInt(), getDouble(), getTimestamp() 등의 메소드 사용하여 해당 데이터출력

import java.sql.ResultSet;
import java.time.LocalDateTime;

public class DBConnEx {

	public static void main(String[] args) throws Exception {
		// DBConn 사용법
		// DBConn.getInstance(); // DB연결
		// DBConn.statementUpdate(); // DB사용
		// DBConn.statementQuery();
		// DBConn.close(); // DB종료
		// resultSet 사용 종료 후 DB를 닫아야 resultSet 사용문제가 없다.
		DBConn.statementUpdate("insert into human values('홍길나',52,151,sysdate)");
		DBConn.statementUpdate("update human set age = 50 where name='홍길나'");
		DBConn.statementUpdate("delete human where name = '홍길나'");
		ResultSet rs = DBConn.statementQuery("select * from human");
		while(rs.next()) {
			String name = rs.getString("name");
			int age = rs.getInt("age");
			double height = rs.getDouble("height");
			LocalDateTime birthday = rs.getTimestamp("birthday").toLocalDateTime();
			
			System.out.println("name: " + name);
			System.out.println("age: " + age);
			System.out.println("height: " + height);
			System.out.println("birthday: " + birthday);
			System.out.println("--------------------------------");
		}
		// DB 닫는 작업
		DBConn.dbClose();
	}
}

3. dto 클래스 추가하기
import java.time.LocalDateTime;
import java.util.Objects;

// 추가해야 할 것들 : getter/setter, 생성자, equals/hashCode, toString

public class HumanDto {
	private String name;
	private Integer age;
	private Double height;
	private LocalDateTime birthday;
	
	@Override
	public String toString() {
		return "HumanDto [name=" + name + ", age=" + age + ", height=" + height + ", birthday=" + birthday + "]";
	}
	
	@Override
	public int hashCode() {
		return Objects.hash(name);
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		HumanDto other = (HumanDto) obj;
		return Objects.equals(name, other.name);
	}

	public HumanDto() {}
	
	public HumanDto(String name, Integer age, Double height, LocalDateTime birthday) {
		super();
		this.name = name;
		this.age = age;
		this.height = height;
		this.birthday = birthday;
	}
	
	public HumanDto(HumanDto dto) {
		super();
		this.name = dto.name;
		this.age = dto.age;
		this.height = dto.height;
		this.birthday = dto.birthday;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Double getHeight() {
		return height;
	}

	public void setHeight(Double height) {
		this.height = height;
	}

	public LocalDateTime getBirthday() {
		return birthday;
	}

	public void setBirthday(LocalDateTime birthday) {
		this.birthday = birthday;
	}
}

(2) UserInput

  • 다양한 유형의 사용자 입력을 처리하는 메소드
  • inputInt(): 인자로 전달된 문자열 출력한 뒤 정수로 입력받아 반환
  • inputDouble(): 인자로 전달된 문자열 출력한 뒤 실수로 입력받아 반환
  • inputString(): 문자열을 입력받아 반환
  • inputLocalDateTime(): yyyy-MM-dd HH:mm:ss 형식으로 입력된 문자열을 파싱하여 LocalDateTime 객체로 반환.
- 이 클래스는 사용자 입력 처리를 캡슐화하여 코드의 재사용성 높임
- 입력값의 유효성 검사와 같은 추가적 기능 제공
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class UserInput {
	private static Scanner sc = new Scanner(System.in);
	
	public static int inputInt(String st) {
		System.out.println(st + " 정수입력>>");
		return Integer.parseInt(sc.nextLine());
	}
	
	public static double inputDouble(String st) {
		System.out.println(st + " 실수입력>>");
		return Double.parseDouble(sc.nextLine());
	}
	
	public static String inputString(String st) {
		System.out.println(st + " 문자입력>>");
		return sc.nextLine();
	}

	public static LocalDateTime inputLocalDateTime(String str) {
		System.out.println(str + " 시간입력(yyyy-MM-dd HH:mm:ss)>>");
		return LocalDateTime.parse(sc.nextLine(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	}
	public static String dataToString(LocalDateTime date) {
		return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	}
}

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import com.human.dto.HumanDto;
import com.human.util.DBConn;
import com.human.util.UserInput;

public class DBConnEx {

	public static void main(String[] args) {
		int input = 0;
		String strMainMenu = "-HumanTable 관리 프로그램---------------------------\n";
		strMainMenu += "| 1. 출력 | 2. 입력 | 3. 삭제 | 4. 수정 | 5. 종료 | \n";
		strMainMenu += "메뉴 번호 ";
		while(input != 5) {
			input = UserInput.inputInt(strMainMenu);
			switch(input) {
			case 1:
				System.out.println("-----------------------------------");
				// select
				ArrayList<HumanDto> resultDtos = new ArrayList<HumanDto>();
				ResultSet rs = DBConn.statementQuery(String.format("select * from human"));
				try {
					while(rs.next()) {
						resultDtos.add(new HumanDto(rs.getString("name")
								, rs.getInt("age"), rs.getDouble("height"), rs.getTimestamp("birthday").toLocalDateTime()));
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				for (HumanDto dto:resultDtos) {
					System.out.println(dto);
				}
				break;
			case 2:
				System.out.println("-----------------------------------");
				// insert
				System.out.println("입력하고자하는 Human데이터 입력");
				HumanDto dto = new HumanDto();
				dto.setName(UserInput.inputString("이름 입력"));
				dto.setAge(UserInput.inputInt("나이 입력"));
				dto.setHeight(UserInput.inputDouble("키 입력"));
				dto.setBirthday(UserInput.inputLocalDateTime("생일 입력"));
				
				String sql = String.format("insert into human values('" + "%s',%d,%f,,to_date('%s', 'YYYY:MM:DD HH24:MI:SS'))"
				, dto.getName(),dto.getAge(),dto.getHeight()
				,dto.getBirthday().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
				
				DBConn.statementUpdate(sql);
				System.out.println("[입력 완료]");
				break;
			case 3:
				System.out.println("-----------------------------------");
				// delete
				System.out.println("삭제할 데이터 입력");
				String name = UserInput.inputString("이름: ");
				sql = String.format("delete human where name = '%s'", name);
				DBConn.statementUpdate(sql);
				System.out.println("[삭제 완료]");
				break;
			case 4:
				System.out.println("-----------------------------------");
				System.out.println("수정할 데이터 입력");
				name = UserInput.inputString("이름: ");
				int age = UserInput.inputInt("나이: ");
				sql = String.format("update human set age = %d where name = '%s'", age, name);
				DBConn.statementQuery(sql);
				System.out.println("[수정 완료]");
				break;
			case 5:
				System.out.println("-----------------------------------");
				System.out.println("프로그램 종료");
				input = 5;
				break;
			default:
				System.out.println("보기에 있는 숫자를 입력하세요");
				break;
			}
		}
		
	}

}
profile
IT 개발자가 되기 위한 기록

0개의 댓글