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);
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();
}
}
(1) DBConn 클래스
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConn {
private DBConn() {}
private static Connection dbConn = null;
private static Statement st = null;
private static ResultSet rs = null;
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;
}
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;
}
}
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;
}
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.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("--------------------------------");
}
DBConn.dbClose();
}
}
3. dto 클래스 추가하기
import java.time.LocalDateTime;
import java.util.Objects;
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;
}
}
- 다양한 유형의 사용자 입력을 처리하는 메소드
- 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("-----------------------------------");
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("-----------------------------------");
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("-----------------------------------");
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;
}
}
}
}