Code example for PreparedStatement

Methods: executeUpdate, getGeneratedKeys, setInt, setNull, setString

0
		int index=0;
		try { 
			PreparedStatement insert = connection.prepareStatement(
					DB_QUERY_INSERT, Statement.RETURN_GENERATED_KEYS);
			if(entity.getApp()!=null){
				insert.setInt(++index, entity.getApp().getId());//id_apk
			}else{ 
				insert.setNull(++index, Types.INTEGER);//id_apk
			} 
 
			//we need to increment the status by one since MySQL starts its enum values at 1 (zero is reserved for errors) 
			insert.setInt(++index, entity.getStatus().ordinal()+1);//analysis_status
			 
			if(entity.getCreationTime()!=null){
				insert.setString(++index, dateFormat.format(entity.getCreationTime()));//analysis_created
			}else{ 
				insert.setNull(++index, Types.DATE);//analysis_created
			} 
			 
			if(entity.getStartTime()!=null){
				insert.setString(++index, dateFormat.format(entity.getStartTime()));//analysis_started
			}else{ 
				insert.setNull(++index, Types.DATE);//analysis_started
			} 
			 
			if(entity.getStopTime()!=null){
				insert.setString(++index, dateFormat.format(entity.getStopTime()));//analysis_stopped
			}else{ 
				insert.setNull(++index, Types.DATE);//analysis_stopped
			} 
			 
			insert.setInt(++index, entity.getHeuristicValue());//heuristic_result
			 
			insert.executeUpdate();
			ResultSet rs = insert.getGeneratedKeys();
			if (rs.next()) {
				id = rs.getInt(1);
			} else { 
				throw new DAOException("Generated keys could not be retrieved!"); 
			}