选择JTable上显示的多个文件,然后从MySQL数据库下载它们

时间:2016-07-08 14:27:33

标签: java mysql swing jtable

我编写了JButton代码,用于从MySQL数据库下载JTable上显示的选定文件。我希望它下载所有选定的文件。最初我能够一次下载一个文件。现在我已经编辑了代码,它什么都不做,并且没有返回任何错误。代码中可能有什么问题。

如何在我的代码中实现这一目标?

我的代码:

private void jButtonDownloadActionPerformed(java.awt.event.ActionEvent evt) {

    int BUFFER_SIZE = 4096;

    try {
         int[] selected_rows= jTable1.getSelectedRows();
         for (int i = 0; i < selected_rows.length;  i++){
             if (i < selected_rows.length - 1 ) {
        String tableClick=(jTable1.getModel().getValueAt(selected_rows[i],i).toString());
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_certificate","root","");
        String sql= "SELECT Cert, Cert_Name FROM certificate WHERE Cert_Code =?" ;
        PreparedStatement pstmt =  con.prepareStatement(sql);
        pstmt.setString(1, tableClick);
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            String filename = rs.getString("Cert_Name");
            Blob blob = rs.getBlob("Cert");
            InputStream inputStream = blob.getBinaryStream();
            String filePath ="C:\\Users\\User\\Downloads\\Documents\\"+filename;
            OutputStream outputStream = new FileOutputStream(filePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            inputStream.close();
            outputStream.close();
            JOptionPane.showMessageDialog(null,"file saved to Documents in your C folder.");
        }}} }
        catch (Exception e)
        {JOptionPane.showMessageDialog(null,e);}}

1 个答案:

答案 0 :(得分:0)

最后我明白了。非常感谢@Thompson。我需要使用JTable.getSelectedRows()而不是JTable.getSelectedRow()然后循环数组,如下所示:

/* Nav Accordion Plugin v1.1.2
************************************/
(function($){
	$.fn.navAccordion = function(options, callback){
		this.each(function(){
			
			//Options
			var settings = $.extend({
				expandButtonText : "+", //Text inside of expand button
				collapseButtonText: "-",  //Text inside of collapse button
				selectedExpand: "true",   //Expand the selected channel
				selectedClass: "selected",  //Class that will be used to detect the currently selected channel - this will check the "parentElement" for this class (the parent <li> by default)
				multipleLevels: "true",  //Apply accordion to all levels - setting this to false will apply the accordion only to the first level
				buttonWidth: "20%",  //Width of accordion expand/collapse button as a percentage or pixels
				buttonPosition: "right",  //Position of button - 'right' is default - you can also choose 'left'
				slideSpeed: "fast",   //Speed of slide animation - "fast", "slow", or number in milliseconds such as 500
				parentElement: "li",  //Parent element type, class or ID - you don't need to change this if you're using a ul > li > ul pattern
				childElement: "ul",   //Child element type, class or ID - you don't need to change this if you're using a ul > li > ul pattern
				headersOnly: false,  //False is default - setting to true will make any link with sub-nav behave as if it were set to header only, making the link inaccessible - this option is useful if you are using the plugin for a non-navigation area 
				headersOnlyCheck: false, // False is default - set to true to apply the accordion only to links that are set as "header only" (have no href)
				delayLink: false,  //Delay following the href of links until after the accordion the has expanded
				delayAmount: null //Time in milliseconds to delay before following href - will use "slideSpeed" by default if nothing else is set
			}, options);
			
			var container = this,
			//Multiple levels variable
				multi = settings.multipleLevels ? '': ' > ' + settings.childElement + ' > ';
				
			//Add class to container
			$(container)
				.addClass('accordion-nav');
			
			//Apply has-subnav class to lis with uls - also add accordion buttons with styles
			$(multi + settings.parentElement, container).each(function(){
				if ( ($(this).contents(settings.childElement).length > 0 
					&& settings.headersOnlyCheck == false) || (!($('> a', this).attr('href')) 
					&& settings.headersOnlyCheck == true) )  
				{
					//Apply Class and styles to parent item
					$(this).addClass('has-subnav')
						.css('position', 'relative')
							.find('>a')
								.css('margin-' + settings.buttonPosition, settings.buttonWidth);
					
					//Add expand button elements
					$(' > ' + settings.childElement, this)
						.before('<span class="accordion-btn-wrap"><a href="#"><span class="accordion-btn accordion-collapsed">' 
						+ settings.expandButtonText + '</span><a href="#"><span class="accordion-btn accordion-expanded">' 
						+ settings.collapseButtonText + '</span></a></span></a>');
						
					//Apply Styles to expand button
					$('.accordion-btn-wrap', this)
						.css({
							'width': settings.buttonWidth, 
							'position': 'absolute', 
							'top': 0, 
							'text-align': 'center', 
							'cursor': 'pointer', 
							'display': 'inline-block'
						})
						.css(settings.buttonPosition, 0);
					$('.accordion-btn ', this)
						.css({
							'display': 'inline-block', 
							'width': '100%'
						});
					$('.accordion-expanded', this)
						.css('display', 'none');
				}
				
				//Apply styles to <a> tags that are set to header only
				if (!($('> a', this).attr('href')) || settings.headersOnly){
					$(this)
						.addClass('accordion-header-only')
							.find('.accordion-btn-wrap')
								.css({
									'width': '100%', 
									'text-align': settings.buttonPosition
								})
								.find('.accordion-btn ')
									.css({
										'width': settings.buttonWidth, 
										'text-align': 'center'
									});
				}
				
				//Delay Link Mode
				if (settings.delayLink && !settings.headersOnly) {
					var currentThis = this,
						speed = settings.delayAmount != null ? settings.delayAmount : settings.slideSpeed;
					if (speed == "fast") {
						speed = 200;
					} else if (speed == "slow") {
						speed = 600;
					}
					$('> a', currentThis).on('click',function(e){
						if (!$('> .accordion-btn-wrap', currentThis).hasClass("accordion-active")) {
							e.preventDefault();
							var href = $(this).attr('href');
							clickToggle($('> .accordion-btn-wrap', currentThis));
							//Go to link after delay
							setTimeout(function(){
								window.location = href;
							}, speed)
						}
					})
				}
				
			});
			
			var selectedNavAccordion = $(settings.parentElement + '.' + settings.selectedClass + ' > .accordion-btn-wrap', container);
			
			//Debounced Button height event listener
			var buttonheightResize = debounce(function(){
				//Run button height
				buttonheight();
				//Expand Selected Channel
				expandSelected();
			}, 250);
			$(window).on('resize', buttonheightResize);
			
			//Set button heights
			buttonheight();
			
			//Expand Selected Channel
			expandSelected();
			
			//On click function
			$(container).on('click', '.accordion-btn-wrap', function(e) {
				e.preventDefault();
				clickToggle(this);
			});
			
			//Callback
			if (typeof callback == "function") {
				callback();
			}
			
			
			/* Functions 
			*******************************/
				//Click Toggle function
				function clickToggle(element) {
					var nextChild = $(element).next(settings.childElement),
						currentExpandBtn = $('.accordion-expanded', element),
						currentCollapseBtn = $('.accordion-collapsed', element),
						parentObj = $(element).closest(settings.parentElement);
					if (nextChild.is(':visible')) {
						nextChild
							.slideUp(settings.slideSpeed);
						$(element)
							.removeClass('accordion-active');
						currentExpandBtn
							.css('display', 'none');
						currentCollapseBtn
							.css('display', 'inline-block');
						parentObj.add(parentObj.siblings('.active')).add(parentObj.find('.active')).removeClass('active');
					} else {
						$(element).closest(settings.childElement).find('.accordion-active')
							.removeClass('accordion-active')
							.next(settings.childElement)
								.slideUp(settings.slideSpeed).prev()
								.find('.accordion-expanded')
									.css('display', 'none')
									.parent().find('.accordion-collapsed')
										.css('display', 'inline-block');
						parentObj.add(parentObj.siblings('.active')).add(parentObj.find('.active')).removeClass('active');
						$(element)
							.addClass('accordion-active');
						nextChild
							.slideToggle(settings.slideSpeed);
						currentExpandBtn
							.css('display', 'inline-block');
						currentCollapseBtn
							.css('display', 'none');
						parentObj.addClass('active');
					}
				}
				
				//Expand Selected Channel Function
				function expandSelected(){
					if(settings.selectedExpand){
						if(!settings.headersOnlyCheck){
						selectedNavAccordion.find('.accordion-expanded')
							.css('display', 'inline-block');
						selectedNavAccordion.find('.accordion-collapsed')
							.css('display', 'none');
						selectedNavAccordion.addClass('accordion-active')
							.next(settings.childElement)
								.css('display', 'block');
						selectedNavAccordion.closest(settings.parentElement)
							.addClass('active');
						} else {
							$(settings.parentElement + '.' + settings.selectedClass + ' > ' + settings.childElement, container)
								.css('display', 'block');
								$(settings.parentElement + '.' + settings.selectedClass).addClass('active');
						}
					}
				}
			
				//Accordion Button Height Function
				function buttonheight(){
					$('.accordion-btn', container).each(function(){
						//Show uls so heights are calculated correctly
						$(settings.parentElement + '.has-subnav > ' + settings.childElement, container)
							.css('display', 'block');
						
						//Calculate and set heights
						var parentItem = $(this).closest(settings.parentElement),
							lineheight =  $('> a', parentItem).innerHeight();
						$(this)
							.css({'line-height': lineheight + 'px', 'height': lineheight});
						
						//Hide uls under lis and reset expand/collapse buttons
						$(settings.parentElement + ((settings.headersOnlyCheck) ? ' ' : '.has-subnav > ') + settings.childElement, container)
							.css('display', 'none');
						$('.accordion-expanded')
							.css('display', 'none');
						$('.accordion-collapsed')
							.css('display', 'inline-block');
					})
				}		
				//Debounce function
				function debounce(func, wait, immediate) {
					var timeout;
					return function() {
						var context = this, args = arguments;
						var later = function() {
							timeout = null;
							if (!immediate) func.apply(context, args);
						};
						var callNow = immediate && !timeout;
						clearTimeout(timeout);
						timeout = setTimeout(later, wait);
						if (callNow) func.apply(context, args);
					};
				};	
		});
	}
})(jQuery);