JDBC 클래식 작업

JDBC의 고전적인 조작을 요약하세요!
1. JDBC는 데이터베이스에 한 줄을 삽입합니다.
 
	
       private static final String USER_INSERT = "insert into user (id, email, password, name) values(null, ?, ?, ?) " ;
	public void saveUser(User user){
		Connection conn = null ;
		PreparedStatement stmt = null ;
		try {
			conn = dateSource.getConnection(); // 
			stmt = conn.prepareStatement(USER_INSERT) ; // 
			stmt.setString(1, user.getEmail()) ; // 
			stmt.setString(2, user.getPassword()) ;
			stmt.setString(3, user.getName()) ;
			
			stmt.execute() ;	// 
		} catch (Exception e) {
			e.printStackTrace() ;
		}finally{
			/*   */
			try {
				if(stmt != null){
					stmt.close() ;
				}
				if(conn != null){
					conn.close() ;
				}
			} catch (Exception e) {
				e.printStackTrace() ;
			}
		}
	}

2. JDBC는 데이터베이스에 한 줄을 업데이트합니다.
 
	private static final String USER_UPDATE = "update user set email=?, password = ?, name=? where id=? " ;
	
	public void updateUser(User user){
		Connection conn = null ;
		PreparedStatement stmt = null ;
		try {
			conn = dateSource.getConnection(); // 
			stmt = conn.prepareStatement(USER_UPDATE) ; // 
			stmt.setString(1, user.getEmail()) ; // 
			stmt.setString(2, user.getPassword()) ;
			stmt.setString(3, user.getName()) ;
			stmt.setInt(4, user.getID()) ;
			
			stmt.execute() ;	// 
		} catch (Exception e) {
			e.printStackTrace() ;
		}finally{
			/*   */
			try {
				if(stmt != null){
					stmt.close() ;
				}
				if(conn != null){
					conn.close() ;
				}
			} catch (Exception e) {
				e.printStackTrace() ;
			}
		}
	}

 
3. 데이터베이스에서 JDBC의 한 줄 조회:
	private static final String USER_QUERY = "select id,email,password,name from user where id=? " ;
	
	public User getUserByID(Integer id){
		Connection conn = null ;
		PreparedStatement stmt = null ;
		ResultSet rs = null ;
		
		try {
			conn = dateSource.getConnection(); // 
			stmt = conn.prepareStatement(USER_QUERY) ; // 
			stmt.setInt(1, id) ; // 
			rs = stmt.executeQuery() ;	// 
			if(rs.next()){
				User user = new User() ;
				user.setID(rs.getInt("id")) ;
				user.setEmail(rs.getString("email")) ;
				user.setPassword(rs.getString("password")) ;
				user.setName(rs.getString("name")) ;
			}
			return user ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}finally{
			/*   */
			try {
				if(rs != null){
					rs.close() ;
				}
				if(stmt != null){
					stmt.close() ;
				}
				if(conn != null){
					conn.close() ;
				}
			} catch (Exception e) {
				e.printStackTrace() ;
			}
		}
	}
 

좋은 웹페이지 즐겨찾기