java的JTable組件顯示mysql數據庫表中的數據以及將JTable表格中的數據存儲到數據庫中

用java的swing組件畫出表格,實現“增加”、“刪除”、“保存”、“退出”的功能,並且與mysql數據庫相連接。

可以實現提取數據庫中表的數據顯示到含有表格的窗體上,也可以將在表格中修改的內容寫入數據庫表中。

我實現以上功能時用了兩個類,其中一個類是MyFrame,另外一個類是PutinStorage。

具體代碼如下(以下代碼均爲完整代碼,經測試成功的):

PutinStorage類:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;

public class PutinStorage {
	// 得到數據庫表數據
	public static Vector getRows(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//數據庫路徑(一般都是這樣寫),test是數據庫名稱
		String name = "root";		//用戶名
		String password = "123456";	//密碼
		Connection conn;
		PreparedStatement preparedStatement = null;

		Vector rows = null;
		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//連接驅動
			conn = DriverManager.getConnection(sql_url, name, password);	//連接數據庫
//			if(!conn.isClosed())
//				System.out.println("成功連接數據庫");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			if(result1.wasNull())
				JOptionPane.showMessageDialog(null, "結果集中無記錄");
			
			rows = new Vector();
			
			ResultSetMetaData rsmd = result1.getMetaData();
					
			while(result1.next()){
				rows.addElement(getNextRow(result1,rsmd));
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功加載驅動。");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功打開數據庫。");
			e.printStackTrace();
		}
		return rows;
	}
	
	// 得到數據庫表頭
	public static Vector getHead(){
		String sql_url = "jdbc:mysql://localhost:3306/haha";	//數據庫路徑(一般都是這樣寫),test是數據庫名稱
		String name = "root";		//用戶名
		String password = "123456";	//密碼
		Connection conn;
		PreparedStatement preparedStatement = null;

		Vector columnHeads = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");		//連接驅動
			conn = DriverManager.getConnection(sql_url, name, password);	//連接數據庫
//			if(!conn.isClosed())
//				System.out.println("成功連接數據庫");
			preparedStatement = conn.prepareStatement("select * from aa");
			ResultSet result1 = preparedStatement.executeQuery();
			
			boolean moreRecords = result1.next();
			if(!moreRecords)
				JOptionPane.showMessageDialog(null, "結果集中無記錄");
			
			columnHeads = new Vector();
			ResultSetMetaData rsmd = result1.getMetaData();
			for(int i = 1; i <= rsmd.getColumnCount(); i++)
				columnHeads.addElement(rsmd.getColumnName(i));
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功加載驅動。");
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("未成功打開數據庫。");
			e.printStackTrace();
		}
		return columnHeads;
	}
	
	// 得到數據庫中下一行數據
	private static Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd) throws SQLException{
		Vector currentRow = new Vector();
		for(int i = 1; i <= rsmd.getColumnCount(); i++){
			currentRow.addElement(rs.getString(i));
		}
		return currentRow;
	}
	
	/*//主函數
	 public static void main(String[] args){
		 getRows();
	}*/
}
MyFrame類:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import per.tushu.storage.PutinStorage;

public class MyFrame extends JFrame{
	
	DefaultTableModel tableModel;		// 默認顯示的表格
	JButton add,del,exit,save;		// 各處理按鈕
	JTable table;		// 表格
	
	JPanel panelUP;	//增加信息的面板
	
	// 構造函數
	public MyFrame(){
		this.setBounds(300, 200, 600, 450);		// 設置窗體大小
		this.setTitle("測試");		// 設置窗體名稱
		this.setLayout(new BorderLayout());	// 設置窗體的佈局方式
				
		// 新建各按鈕組件
		add = new JButton("增加");
		del = new JButton("刪除");
		save = new JButton("保存");
		exit = new JButton("退出");
		
		panelUP = new JPanel();		// 新建按鈕組件面板
		panelUP.setLayout(new FlowLayout(FlowLayout.LEFT));	// 設置面板的佈局方式
		
		// 將各按鈕組件依次添加到面板中
		panelUP.add(add);
		panelUP.add(del);
		panelUP.add(save);
		panelUP.add(exit);
		
		// 取得haha數據庫的aa表的各行數據
		Vector rowData = PutinStorage.getRows();
		// 取得haha數據庫的aa表的表頭數據
		Vector columnNames = PutinStorage.getHead();
		
		
		// 新建表格
		tableModel = new DefaultTableModel(rowData,columnNames);	
		table = new JTable(tableModel);
		
		JScrollPane s = new JScrollPane(table);
		
		// 將面板和表格分別添加到窗體中
		this.add(panelUP,BorderLayout.NORTH);
		this.add(s);
		
		// 事件處理
		MyEvent();
		
		this.setVisible(true);		// 顯示窗體
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		 // 設置窗體可關閉
	}
	
	// 事件處理
	public void MyEvent(){
		
		// 增加
		add.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// 增加一行空白區域
				tableModel.addRow(new Vector());
			}
			
		});
		
		// 刪除
		del.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				// 刪除指定行
				int rowcount = table.getSelectedRow();
				if(rowcount >= 0){
					tableModel.removeRow(rowcount);
				}
			}
			
		});
		
		/**
		 * 保存
		 * 我的解決辦法是直接將aa表中的全部數據刪除,
		 * 將表格中的所有內容獲取到,
		 * 然後將表格數據重新寫入aa表
		 */
		save.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {	
				int column = table.getColumnCount();		// 表格列數
				int row = table.getRowCount();		// 表格行數
				
				// value數組存放表格中的所有數據
				String[][] value = new String[row][column];
				
				for(int i = 0; i < row; i++){
					for(int j = 0; j < column; j++){
						value[i][j] = table.getValueAt(i, j).toString();
					}
				}
				
				// 以下均爲對數據庫的操作
				String sql_url = "jdbc:mysql://localhost:3306/haha";	//數據庫路徑(一般都是這樣寫),haha是數據庫名稱
				String name = "root";		//用戶名
				String password = "123456";	//密碼
				Connection conn;
				PreparedStatement preparedStatement = null;

				try {
					Class.forName("com.mysql.jdbc.Driver");		//連接驅動
					conn = DriverManager.getConnection(sql_url, name, password);	//連接數據庫
					if(!conn.isClosed())
						System.out.println("成功連接數據庫");
					
					// 刪除aa表中所有數據
					preparedStatement = conn.prepareStatement("delete from aa where true");
					preparedStatement.executeUpdate();
					
					// 將value數組中的數據依次存放到aa表中
					for(int i = 0; i < row; i++){
						preparedStatement = conn.prepareStatement("insert into aa values(" + Integer.parseInt(value[i][0]) + ",'" + value[i][1] + "')");
						preparedStatement.executeUpdate();
					}
					
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					System.out.println("未成功加載驅動。");
					e1.printStackTrace();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					System.out.println("未成功打開數據庫。");
					e1.printStackTrace();
				}
				
				// 保存後退出
				System.exit(0);
			}
		});
		
		// 退出
		exit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
				System.exit(0);
			}
				
		});
	}
	
	// 主函數
	public static void main(String[] args){
		new MyFrame();
	}
}
執行以上代碼的時候,最初顯示的窗體如下所示:

點擊增加按鈕並寫入需要增加的內容(我增加了三次)如下圖:

點擊刪除按鈕,刪除指定行(我刪除了第2行和第4行),如下圖:

點擊保存按鈕,會發現窗口也關閉了。這是你可以再重新執行代碼,會發現出現的表格頁面與上圖一樣。

點擊退出按鈕,關閉窗口。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章