본문 바로가기

JDBC

Select

executeUpdate(sql); insert, delete, update
executeQuery(sql); select

preparedstatement는 패션마크

 

 

public class mainClass {

	public static void main(String[] args) {
		DBConnection.initConnection();

		SelectTest st = new SelectTest();
		
//		String id = "1"; 	//찾으려는 데이터
//		UserDto dto = st.search(id);
//		if (dto != null) {
//			System.out.println(dto.toString());
//			
//		}else {
//			System.out.println("등록되어있지 않은 id입니다");
//		}
//		
//		id = "bcd";
//		dto = st.Select(id);
//		if(dto != null) {
//			System.out.println(dto.toString());			
//		}		
//		else {
//			System.out.println("등록되어 있지 않은 id입니다");
//		}
		
		List<UserDto> list = st.getUserList();
		for (UserDto user : list) {
			System.out.println(user.toString());
		}
	}
}

 

getUser

	public List<UserDto> getUserList() {
		String sql = " SELECT ID, NAME, AGE, JOINDATE" + " FROM USERTEST";
		
		Connection conn = DBConnection.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		
		List<UserDto> list = new ArrayList<UserDto>();
		
		try {
			psmt = conn.prepareStatement(sql);
			rs = psmt.executeQuery();
			
			while(rs.next()) {	//다수의 데이터는 while문으로 데이터가있을 때까지 돌려줌
				String id = rs.getString("id");
				String name = rs.getString("name");
				int age = rs.getInt("age");
				String joindate = rs.getString("joindate");
				
				UserDto dto = new UserDto(id, name, age, joindate);
				
				list.add(dto);	//추가적으로 데이터를 넣어줌
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(psmt, conn, rs);
		}
		return list;
	}
}

 

 

Dto

public class UserDto implements Serializable{	//직렬화

	private String id;
	private String name;
	private int age;
	private String joindate;	//date도 String!!!!!!
	
	public UserDto() {

	}
	public UserDto(String id, String name, int age, String joindate) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.joindate = joindate;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getJoindate() {
		return joindate;
	}
	public void setJoindate(String joindate) {
		this.joindate = joindate;
	}
	@Override
	public String toString() {
		return "UserDto [id=" + id + ", name=" + name + ", age=" + age + ", joindate=" + joindate + "]";
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'JDBC' 카테고리의 다른 글

Delete  (0) 2020.06.30
Select 한개의 데이터  (0) 2020.06.30
Update  (0) 2020.06.30
JDBC 기본 연결  (0) 2020.06.30
INSERT (기본 -> DBclose 수정)  (0) 2020.06.30