Java窗口小程序——显示SQL数据库中的多行数据


import com.test.database.DBManager;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.io.*;
import java.net.URLEncoder;
import java.util.Vector;
   public class Study extends HttpServlet
   {
	private final static long serialVersionUID = 1L;
    public Study() {
        super();
    }
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    	response.setContentType("text/html; charset=UTF-8" );
        request.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter(); 
    	JFrame f=new JFrame();   	 
    	JTable t=new JTable();   	 
    	DefaultTableModel dt=new DefaultTableModel();   	 
    	t.setModel(dt);
        
    	DBManager db = new DBManager();   	
        String sql = "select * from " + DBManager.TABLE_NAME_Xiao;

        ResultSet rst = db.query(sql);    
        try{       
        	ResultSetMetaData rsmd = rst.getMetaData();                 
        	int numberOfColumns=rsmd.getColumnCount();                
        	int b=1;          
        	//以下是显示数据库中的列名的代码           
        	while(b<=numberOfColumns)                 	
        	{           
        		dt.addColumn(rsmd.getColumnName(b));           
        		b++;           
        	}        
        	             
        	while(rst.next())                 	
        	{   
        		//以下是在表格中显示数据中的内容      
        		Vector newRow=new Vector(); 
        		int c=1; 
        		while(c<=numberOfColumns) 
        		{ 
        		newRow.addElement(rst.getString(c)); 
        		c++; 
        		} 
        		dt.addRow(newRow);         
        	}        
        }
        catch(Exception e)
           {           
        	e.printStackTrace();         
           } 
        JScrollPane s = new JScrollPane(t);
        f.getContentPane().add(s, BorderLayout.CENTER);
        f.setTitle("表");
        f.pack();
        f.setVisible(true);  
        f.addWindowListener(new WindowAdapter() {          
        	public void windowClosing(WindowEvent e) {               
        		System.exit(0);          
        	};
        	});
        out.print(dt);  //这里我把服务端成功后,返回给客户端的是DefaultTableModel
        } 
 
    public static void main(String args[]) 
    {	 
    	new Study();
    }
}

运行之后的效果如下图所示

Java窗口小程序——显示SQL数据库中的多行数据_第1张图片

转载于:https://my.oschina.net/u/3724795/blog/1648486

你可能感兴趣的:(Java窗口小程序——显示SQL数据库中的多行数据)