JAVA GUI 實現數據庫可視化操作(簡易版)

    學習了java的可視化控件還有數據庫,我們可以寫一個簡單的可以實現增刪改查的界面,界面效果大概如下(界面不太美觀,過幾天我會寫一個JavaWeb項目來在瀏覽器上實現此功能,今天寫下此博客來記錄一下遇到的問題和解決方法)以下可以直接跳轉到您想看的位置,點擊跳轉 ↓↓↓


- 先放一張截圖:

在這裏插入圖片描述

            顯然我們可以看到此軟件的佈局和功能:

  • 佈局:
  1. 整體的面板採用的是BorderLayout佈局方式:
          窗口大小不可以調整,但是窗口每次更新數據後會自動調整窗口的高度,來滿足更多的數據能夠輸出到窗口中.
          在整體佈局的上面(“North”)部分是一個獨立的畫板,來顯示數據庫表格中的所有數據,並按照一定格式顯示出來,不可被編輯.
          在整體佈局的Center部分也是獨立的畫板,只用來顯示提示用戶輸入的信息.
          在佈局的South(底部),添加了兩行,如圖中所示,一行是輸入框一行是功能按鈕.在右下角還有一個提示框,用來提示用戶正確操作.
          修改操作沒有添加,因爲這幾個輸入框不能完全滿足所有功能,修改功能也可以先刪除再添加,效果一樣。
  • 功能:
          如大家所見,實現了增刪查的功能,至於改的操作,需要單獨的界面,就暫時沒有寫.可以通過先刪除,後增加的方式一樣可以實現.
  1. 在添加時候:
    -輸入數據不能爲空,爲空有報錯機制,會提示用戶;
    -添加的信息中學號不能重複,右下角也會給出提示
    -輸入數據格式要正確,學號和年齡都用的整型變量來存儲,在輸入的時候添加了代碼的限制,只能將數字輸入.
  2. 刪除的時候:
    -用戶根據學號來刪除,不重複,防止誤刪;
    -輸入爲空會提示
  3. 查詢時候:
    -用戶一次只能根據一條信息來查詢(學號\姓名\年齡等均可,但是隻能輸入一項)
    -不輸入或者輸入多項會提示用戶.

在這裏插入圖片描述

  1. 在java項目中使用jar包(本次使用):
        首先我們找到jar包的地址,然後在環境變量中將路徑添加在CLASSPATH裏面(注意分號結尾不加分號):
    在這裏插入圖片描述
  • 現在我們就可以連接數據庫了。

  • 在設計的過程中遇到了幾個問題
  1. 首先便是jar包的導入了,上面已經提到
  2. 其次就是關於在插入數據時侯,中文亂碼問題的解決:
    這裏我用的是Navicat,連接的是MySQL數據庫,解決方法很簡單,將useUnicode=true&characterEncoding=utf8";添加到URL地址就好(具體請看代碼):
"jdbc:mysql://localhost:3306/name?useUnicode=true&characterEncoding=utf8";
  1. 浪費時間挺長的一項: 空指針異常!
    特別是在傳遞數據的時候,添加按鈕監聽器之後,取出用戶輸入的數據,然後再將數據輸出或者轉換成SQL語句.特別是在寫查詢語句的時候,因爲查詢的結果要輸出,保存在字符串數組中,數組沒有設定爲static類型,導致一直報空指針異常的錯誤.卡在這好久.改成static類型的數組來存儲數據就解決了.
  2. 關於轉義字符:
    這個倒是很容易想到,不過還是錯了一次,轉義字符,比如:
String sql_1 = "insert into hello values(" + sno +",\'"+ sname +"\',\'" +ssex
									+"\'," + sage + ",\'" + sdept + "\')";

我們來看運行效果:

在這裏插入圖片描述
添加成功後會自動跳出一個新窗口來更新數據:

在這裏插入圖片描述

如果學號重複,會提示:
在這裏插入圖片描述
如果輸入不合規也有報錯:
在這裏插入圖片描述

在刪除時候,若輸入的學號不存在:
在這裏插入圖片描述
如果查詢時候輸入多項信息:
在這裏插入圖片描述
查詢成功後,會跳出一個新窗口來重新輸出查詢的結果.
在這裏插入圖片描述

  • 源代碼詳解如下(一切盡在註釋之中):
    我們在此將數據庫連接代碼和處理數據代碼分開,結構如下:
    在這裏插入圖片描述
    其中,DBConnect.java顯然是連接數據庫的文件:
    數據庫連接很簡單,分三步來就可以
  1. 導入驅動
  2. 連接數據庫
  3. 提交查詢語句
    本文件很簡單,具體代碼如下:
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConnect {
	private static String DRIVER = "com.mysql.jdbc.Driver";//注意不同的數據庫此項不同,可百度到相應的語句.
	private static String URL = "jdbc:mysql://localhost:3306/usertest?useUnicode=true&characterEncoding=utf8";//在後面加的useUnicode=true&characterEncoding=utf8使數據庫能夠識別中文字符,解決亂碼問題.
	private static String USERNAME = "your_username";//數據庫用戶名
	private static String PASSWORD = "your_password";//數據庫密碼
	private static Connection connection = null;
	
	@SuppressWarnings("rawtypes")
	Statement statement = null;	//狀態
	ResultSet result= null;		//結果集
	
	static {
		try {
//			導入驅動,加載具體的驅動類
			Class.forName(DRIVER);
			System.out.println("連接數據庫中...");
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		
		try {
			connection = (Connection) DriverManager.getConnection(URL , USERNAME , PASSWORD);
			System.out.println("數據庫連接成功!");
		}catch(SQLException e) {
			System.out.println("數據庫連接失敗!");
			e.printStackTrace();
		}
		
		return (Connection) connection;
		
	}

下面來看主要的代碼,首先我們來看查詢的方法(解釋都在註釋中):

	public void select_s(String sql_1) {
	//在這裏我們傳過來一個參數sql_1;我們會將sql_1初始化爲" ",我們調用此方法是時候,會傳來一個要進行上傳運行的sql語句,或者傳過來" "則代表沒有語句要執行.下面有判斷機制:
		DBConnect dbConnect = new DBConnect();		//首先我們導入DBConnect類來連接數據庫
		Connection connection = (Connection) dbConnect.getConnection();	
		Statement statement = null; 
		/*我們在此選擇的是Statement也可以用PreparedStatement,
		StatemenI和PreparedStatement都可以用於把sq1語句從java程序中發送到指定數據庫,並執行sq1語句;
		若:直接使用Statement,驅動程序一般不會對sql語句作處理而直接交給數據庫;
		使用PreparedStament,形成預編譯的過程,並且會對語句作字集的轉換.
		所以一般使用PreparedStament效率會更高一點;
		*/
		
		try {
			statement = (Statement) connection.createStatement();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		ResultSet resultSet = null;
		if(sql_1 != " ") {//如果sql_1中的字符串是查詢語句
			try {
				statement.executeUpdate(sql_1);//進行上傳SQL語句的處理
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
			String sql = "select * from hello where Sno > 0"; //查詢出所有的數據的語句
		try {
				resultSet = statement.executeQuery(sql);//保存在結果集中
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
		try
		{
			while(resultSet.next())
			{
				int Sno = resultSet.getInt("Sno");
				String name = resultSet.getString("Sname");
				String Ssex = resultSet.getString("Ssex");
				String Sdept = resultSet.getString("Sdept");
				int Sage = resultSet.getInt("Sage");
				student_number[i] = Sno;//將學號存入數組,並且固定格式
				date_string[i++] = "學號:" + Sno + ",姓名:" +name + ",性別:" + 
						Ssex + ",年齡:" + Sage + "歲,專業:" + Sdept;
						//用到了變量i,i的大小就是數據庫中數據的數目,我們用它來調節窗口,輸出數據.
			}
			resultSet.close();
		}catch(SQLException q)
		{
			q.printStackTrace();
		}finally {
			try {
				statement.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
			try {
				connection.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
		}
	}

  • 下面是圖形界面的設計和監聽器的使用:
public Change() {
		
		String sql_q = " "; //我們要調用上面的方法來獲取數據,先輸出所有的數據到窗口,所以初始化方法的參數
				
		select_s(sql_q);
		
		setTitle("數據庫作業");
		this.setBackground(Color.LIGHT_GRAY);
		this.setLocation(500, 300);			//設置窗口出現位置
		this.setSize(400, 45*i);		//自動隨數據數目增多高度變大,排版較好
        this.setResizable(false);	//不可以調整窗口大小
        /*然後添加一個畫板,來設計第一部分(輸出數據的部分)
        容易發現,我在此處新建了兩個畫板,
        因爲我們正常輸出需要一個
        而我們的查詢語句查詢的結果輸出也需要一個畫板
        所以在此設置兩個畫板,通過查詢語句結果集中數據的個數K的值來
        決定用哪一個輸出.
		*/
        JPanel date1 = new JPanel();	
        date1.setLayout(new GridLayout(k + 1, 1, 1, 1)); //這是查詢語句對應的畫板
        
        JPanel date = new JPanel();
        date.setLayout(new GridLayout(i + 1, 1, 1, 1));//這是輸出全部數據用到的畫板
        if(k > 0) {
        	for(int l = 0 ; l < k ; l++) {
        		text3[l] = new JTextField(date_string2[l]);	//如果查詢語句對應的結果個數不爲0就輸出,且每次輸出之後都會重置k的值,所以不用擔心.
        		text3[l].setEditable(false);
        	}
        	for(int j = 0 ; j < k; j++) {
            	date1.add(text3[j]);//剛纔new了結果集文本框數組,我們循環將它們添加到畫板
            }
        }else {
        	
        	for(int j = 0 ; j < i; j++) {
            	text[j] = new JTextField(date_string[j]);
            	text[j].setEditable(false);//同理
            }
            for(int j = 0 ; j < i; j++) {
            	date.add(text[j]);
            }
        }
       
 
        /*接下來是添加的另一個面板(提示用戶輸入的對應信息的畫板,
        這裏我用的JButton,當然也可以用JTextField.*/
        JPanel use = new JPanel();
        use.setLayout(new GridLayout(1,1 , 6 ,0));
        for(int j = 0 ; j < text_name.length ; j++) {
        	text2[j] = new JButton(text_name[j]);
        	//我們在上面已經準備好了字符串數組,將提示內容循環導入就好
        	//先創建按鈕,再導入畫板
        }
        for(int j = 0 ; j < text_name.length ; j++) {
        	use.add(text2[j]);
        }
 
        JPanel input = new JPanel();//這裏是組成大畫板的最後一個畫板,在窗口的底部
        //包含兩行,第一行,給用戶提供五個輸入框,分別賭贏提示的輸入內容.
        //第二行,對應功能按鈕,和兩個提示文本框
        input.setLayout(new GridLayout(2,1,6,10));//間距改的比較大一些,看得舒服
        for(int j = 0 ; j < text_name.length ; j++) {
        	input_name[j] = new JTextField();
        	input_name[j].setEditable(true);
        }
        
        for(int j = 0 ; j < text_name.length ; j++) {
        	input.add(input_name[j]);
        }
        
        temp[0] = new JTextField("選擇功能");	//第一個提示框
        temp[0].setEditable(false);
        temp[0].setHorizontalAlignment(JTextField.CENTER);
        temp[0].setForeground(Color.red);
        input.add(temp[0]);
        for(int j = 0 ; j < 3 ; j++) {
        	select_menu[j] = new JButton(select[j]);
        }
        for(int j = 0 ; j < 3 ; j++) {
        	input.add(select_menu[j]);
        }
        if(count == 0) {	
        	temp[1] = new JTextField();	
        	//第二個提示框,根據不同的標誌的數值,來判斷是否成功的運行,防止程序崩潰
        }else if(count == 1) {
        	temp[1] = new JTextField("添加成功");
        }else if(count == 2) {
        	temp[1] = new JTextField("刪除成功");
        }else if(count == 3) {
        	temp[1] = new JTextField("查詢成功");
        }
        
        temp[1].setEditable(false);
        temp[1].setHorizontalAlignment(JTextField.CENTER); //文字調到中心
        temp[1].setForeground(Color.RED);	//紅色提醒
        input.add(temp[1]);
        
//註冊監聽器(容易理解)
//直接在這裏註冊功能按鈕按下的時候的監聽器,對於我來說比較容易理解
        select_menu[0].addActionListener(new ActionListener() {//這個按鈕對應增加操作
			public void actionPerformed(ActionEvent e) {
				String a = e.getActionCommand();
				int n = 0;//輸入的五個數據中爲空的個數,
				if(a.equals("增")) {
					for(int j = 0 ; j < 5 ; j++) {
						if(input_name[j].getText().equals(""))
							n++;
					}//輸入有一個是空的都會報錯,提醒用戶
					int q = 0;//判斷學號是否重複;
					if(n == 0) {
						int sno = Integer.parseInt(input_name[0].getText());
						for(int j = 0 ; j < i ; j++) {
							if(sno == student_number[j]) {
								temp[1].setText("學號重複");
								q = 1;//學號重複標誌
							}
						}
					if(q != 1) {//如果學號沒重複,進行插入操作
							String sname = input_name[1].getText();
							String ssex = input_name[2].getText();
							int sage = Integer.parseInt(input_name[3].getText());
							String sdept = input_name[4].getText();
							String sql_1 = "insert into hello values(" + sno +",\'"+ sname +"\',\'" +ssex
									+"\'," + sage + ",\'" + sdept + "\')";
									//注意轉義字符
							System.out.println(sql_1);//輸出到控制檯進行測試
							select_s(sql_1);//進行上傳查詢語句
							Change aa = new Change();
							//因爲進行了數據更新操作,所以需要重新同步一下數據.
							aa.setVisible(true);
							temp[1].setText("添加成功");
							aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
						
						}
					}else {
						temp[1].setText("輸入爲空");
					}
						
				}
			}
        	
        });
        select_menu[1].addActionListener(new ActionListener() {//這個按鈕對應刪除操作

			public void actionPerformed(ActionEvent e) {
				int exist = 0;//要刪除的學生是否存在,(利用之前查詢到的結果加快處理)
				if(input_name[0].getText().equals("")) {//沒有輸入就點擊刪除,很顯然錯誤
					temp[1].setText("學號爲空");
				}else {
					int sno = Integer.parseInt(input_name[0].getText());//String轉int
					for(int j = 0 ; j < i ; j++) {
						if(sno == student_number[j]) {
							exist = 1;
						}
					}
					if(exist == 1) {//要刪除的對象存在
						String sql = "delete from hello where Sno = " + sno;
						select_s(sql );
						Change aa = new Change();
						aa.setVisible(true);
						temp[1].setText("刪除成功");
						aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					}else {//要刪除的對象不存在,顯然學號輸入錯誤
						temp[1].setText("學號錯誤");
					}
				}
				
			}
        	
        });
        select_menu[2].addActionListener(new ActionListener() {//這個按鈕對應查詢操作

			public void actionPerformed(ActionEvent e) {
				
				String sql = "";
				int n = 0;//五個輸入框輸入不爲空的數目(一次只能根據一項原則查詢)
				int temp1 = -1;//記錄下標(根據什麼進行查詢0是學號,1是姓名,2是性別,對應五個輸入框)
				for(int j = 0 ; j < 5 ; j++) {
					if(!input_name[j].getText().equals("")) {
						n++;
						temp1 = j;
					}
				}
				if(n == 0) {//都爲空
					temp[1].setText("輸入爲空!");
				}else if(n > 1) {//查詢規則大於1
					temp[1].setText("別輸入多項");
				}else if(n == 1) {
				//剛好按照一個條件來查詢,正確,下面進行分類(switch語句會更好一些)
					if(temp1 == 0) {
						//學號
						int sno = Integer.parseInt(input_name[temp1].getText());
						sql = "select * from hello where Sno = " + sno;
					}else if(temp1 == 3) {
						//年齡
						int age = Integer.parseInt(input_name[temp1].getText());
						sql = "select * from hello where Sage = " + age;
					}else if(temp1 == 1){
					//姓名
						String name = input_name[temp1].getText();
						sql = "select * from hello where Sname = \'" + name +"\'"; 
					}else if(temp1 == 2) {
						//性別
						String sex = input_name[temp1].getText();
						sql = "select * from hello where Ssex = \'" + sex +"\'";
					}else if(temp1 == 4) {
						//專業
						String dept = input_name[temp1].getText();
						sql = "select * from hello where Sdept = \'" + dept +"\'"; 
					}
					//我們在這裏需要進行單獨的一次查詢,調用函數會有空指針異常的報錯,
					//回頭再測試解決方法吧.
					//過程已經介紹過
					DBConnect dbConnect = new DBConnect();
					Connection connection = (Connection) dbConnect.getConnection();
					Statement statement = null;
					
					try {
						statement = (Statement) connection.createStatement();
					}catch(SQLException e2) {
						e2.printStackTrace();
					}
					ResultSet resultSet2 = null;
					try {
						resultSet2 = statement.executeQuery(sql);
				}catch(SQLException e2) {
					e2.printStackTrace();
				}
				
				try
				{
					while(resultSet2.next())
					{
						int Sno = resultSet2.getInt("Sno");
						String name = resultSet2.getString("Sname");
						String Ssex = resultSet2.getString("Ssex");
						String Sdept = resultSet2.getString("Sdept");
						int Sage = resultSet2.getInt("Sage");
						date_string2[k++] = "學號:" + Sno + ",姓名:" +name + ",性別:" + 
								Ssex + ",年齡:" + Sage + "歲,專業:" + Sdept;
						
					}
					resultSet2.close();
				}catch(SQLException q)
				{
					q.printStackTrace();
				}finally {
						try {
							statement.close();
						} catch (SQLException e2) {
							
							e2.printStackTrace();
						}
						try {
							connection.close();
						} catch (SQLException e2) {
							
							e2.printStackTrace();
						}
					}
					
					Change aa = new Change();
					aa.setVisible(true);
					temp[1].setText("查詢成功");
					aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				}
				k = 0;	//輸出結果後,將K置零,前面已提到
			}
        	
        });
       
        //getContentPane方法獲取當前的總面板,我們設置以下屬性即可.
        getContentPane().setLayout(new BorderLayout(3, 2));
        if(k > 0) {//對應前面說到的,按照K的值來選擇輸出全部還是輸出查詢功能對應的結果集
        	getContentPane().add("North" , date1);	//North對應頂部
        }else
        	getContentPane().add("North" , date);		
        getContentPane().add("Center" , use);
        getContentPane().add("South" , input);//South對應底部
        input.setPreferredSize(new Dimension(0,80));//設置底部控件,更平衡一些.
	}
  • 下面附上Change.java完整代碼:
package 數據庫;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.mysql.jdbc.Connection;

public class Change extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;
	private JTextField text[] = new JTextField[100];//輸出表中全部信息用到的文本框
	private JTextField text3[] = new JTextField[100];//輸出查詢結果的新面板用到的文本框
	String date_string[] = new String[100];			//存儲數據庫表中所有數據爲String格式(配合上面的text[]使用)
	static String date_string2[] = new String[100];	//存儲查詢操作後的數據爲字符串格式,(和text3[]配合使用)
	
	private String[] text_name = {"學號", "姓名" , "性別" , "年齡" , "系別"};
	private JButton text2[] = new JButton[text_name.length];
	private JTextField [] input_name = new JTextField[text_name.length];
	private JTextField [] temp = new JTextField[2];
	private JButton [] select_menu = new JButton[4];
	private String[] select = {"增", "刪"  ,"查"};
	int i = 0;
	static String asa;
//	String date;
	static int k = 0;//用來查詢
	int [] student_number = new int[100];//儲存學生的學號(添加時候防重複)
	int count = 0;//用來判斷是增刪改查其中的一個
	public void select_s(String sql_1) {
		DBConnect dbConnect = new DBConnect();
		Connection connection = (Connection) dbConnect.getConnection();
		Statement statement = null;
		
		try {
			statement = (Statement) connection.createStatement();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		ResultSet resultSet = null;
		if(sql_1 != " ") {
			try {
				statement.executeUpdate(sql_1);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
			String sql = "select * from hello where Sno > 0";
			
		try {
				resultSet = statement.executeQuery(sql);
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
		try
		{
			while(resultSet.next())
			{
				int Sno = resultSet.getInt("Sno");
				String name = resultSet.getString("Sname");
				String Ssex = resultSet.getString("Ssex");
				String Sdept = resultSet.getString("Sdept");
				int Sage = resultSet.getInt("Sage");
				student_number[i] = Sno;//將學號存入數組
				date_string[i++] = "學號:" + Sno + ",姓名:" +name + ",性別:" + 
						Ssex + ",年齡:" + Sage + "歲,專業:" + Sdept;
			}
			resultSet.close();
		}catch(SQLException q)
		{
			q.printStackTrace();
		}finally {
			try {
				statement.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
			try {
				connection.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
		}
	}

	
	public Change() {
		
		String sql_q = " ";
		
		select_s(sql_q);
		
		setTitle("數據庫作業");
		this.setBackground(Color.LIGHT_GRAY);
		this.setLocation(500, 300);
		this.setSize(400, 45*i);		//自動隨數據數目增多高度變大,排版較好
        this.setResizable(false);	
        
        JPanel date1 = new JPanel();
        date1.setLayout(new GridLayout(k + 1, 1, 1, 1));
        
        JPanel date = new JPanel();
        date.setLayout(new GridLayout(i + 1, 1, 1, 1));
        if(k > 0) {
        	for(int l = 0 ; l < k ; l++) {
        		text3[l] = new JTextField(date_string2[l]);
        		text3[l].setEditable(false);
        	}
        	for(int j = 0 ; j < k; j++) {
            	date1.add(text3[j]);
            }
        }else {
        	
        	for(int j = 0 ; j < i; j++) {
            	text[j] = new JTextField(date_string[j]);
            	text[j].setEditable(false);
            }
            for(int j = 0 ; j < i; j++) {
            	date.add(text[j]);
            }
        }
        
        //接下來是添加的面板:
        JPanel use = new JPanel();
        use.setLayout(new GridLayout(1,1 , 6 ,0));
        for(int j = 0 ; j < text_name.length ; j++) {
        	text2[j] = new JButton(text_name[j]);
        }
        for(int j = 0 ; j < text_name.length ; j++) {
        	use.add(text2[j]);
        }
 
        JPanel input = new JPanel();
        input.setLayout(new GridLayout(2,1,6,10));
        for(int j = 0 ; j < text_name.length ; j++) {
        	input_name[j] = new JTextField();
        	input_name[j].setEditable(true);
        }
        
        for(int j = 0 ; j < text_name.length ; j++) {
        	input.add(input_name[j]);
        }
        
        temp[0] = new JTextField("選擇功能");
        temp[0].setEditable(false);
        temp[0].setHorizontalAlignment(JTextField.CENTER);
        temp[0].setForeground(Color.red);
        input.add(temp[0]);
        for(int j = 0 ; j < 3 ; j++) {
        	select_menu[j] = new JButton(select[j]);
        }
        for(int j = 0 ; j < 3 ; j++) {
        	input.add(select_menu[j]);
        }
        if(count == 0) {
        	temp[1] = new JTextField();
        }else if(count == 1) {
        	temp[1] = new JTextField("添加成功");
        }else if(count == 2) {
        	temp[1] = new JTextField("刪除成功");
        }else if(count == 3) {
        	temp[1] = new JTextField("查詢成功");
        }
        
        temp[1].setEditable(false);
        temp[1].setHorizontalAlignment(JTextField.CENTER);
        temp[1].setForeground(Color.RED);
        input.add(temp[1]);
        
//註冊監聽器(容易理解)
        select_menu[0].addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String a = e.getActionCommand();
				int n = 0;//輸入爲空的個數
				if(a.equals("增")) {
					for(int j = 0 ; j < 5 ; j++) {
						if(input_name[j].getText().equals(""))
							n++;
					}
					int q = 0;//判斷學號是否重複;
					if(n == 0) {
						int sno = Integer.parseInt(input_name[0].getText());
						for(int j = 0 ; j < i ; j++) {
							if(sno == student_number[j]) {
								temp[1].setText("學號重複");
								q = 1;
							}
						}
					if(q != 1) {
							String sname = input_name[1].getText();
							String ssex = input_name[2].getText();
							int sage = Integer.parseInt(input_name[3].getText());
							String sdept = input_name[4].getText();
							String sql_1 = "insert into hello values(" + sno +",\'"+ sname +"\',\'" +ssex
									+"\'," + sage + ",\'" + sdept + "\')";
							System.out.println(sql_1);
							select_s(sql_1);
							Change aa = new Change();
							aa.setVisible(true);
							temp[1].setText("添加成功");
							aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
						
						}
					}else {
						temp[1].setText("輸入爲空");
					}
						
					
				}
			}
        	
        });
        select_menu[1].addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int exist = 0;
				if(input_name[0].getText().equals("")) {
					temp[1].setText("學號爲空");
				}else {
					int sno = Integer.parseInt(input_name[0].getText());
					for(int j = 0 ; j < i ; j++) {
						if(sno == student_number[j]) {
							exist = 1;
						}
					}
					if(exist == 1) {
						String sql = "delete from hello where Sno = " + sno;
						select_s(sql );
						Change aa = new Change();
						aa.setVisible(true);
						temp[1].setText("刪除成功");
						aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					}else {
						temp[1].setText("學號錯誤");
					}
				}
				
			}
        	
        });
        select_menu[2].addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				
				String sql = "";
				int n = 0;//輸入不爲空的數目
				int temp1 = -1;//記錄下標
				for(int j = 0 ; j < 5 ; j++) {
					if(!input_name[j].getText().equals("")) {
						n++;
						temp1 = j;
					}
				}
				if(n == 0) {
					temp[1].setText("輸入爲空!");
				}else if(n > 1) {
					temp[1].setText("別輸入多項");
				}else if(n == 1) {
					if(temp1 == 0) {
						//學號
						int sno = Integer.parseInt(input_name[temp1].getText());
						sql = "select * from hello where Sno = " + sno;
					}else if(temp1 == 3) {
						int age = Integer.parseInt(input_name[temp1].getText());
						sql = "select * from hello where Sage = " + age;
					}else if(temp1 == 1){
						String name = input_name[temp1].getText();
						sql = "select * from hello where Sname = \'" + name +"\'"; 
					}else if(temp1 == 2) {
						String sex = input_name[temp1].getText();
						sql = "select * from hello where Ssex = \'" + sex +"\'";
					}else if(temp1 == 4) {
						String dept = input_name[temp1].getText();
						sql = "select * from hello where Sdept = \'" + dept +"\'"; 
					}
					DBConnect dbConnect = new DBConnect();
					Connection connection = (Connection) dbConnect.getConnection();
					Statement statement = null;
					
					try {
						statement = (Statement) connection.createStatement();
					}catch(SQLException e2) {
						e2.printStackTrace();
					}
					ResultSet resultSet2 = null;
					try {
						resultSet2 = statement.executeQuery(sql);
				}catch(SQLException e2) {
					e2.printStackTrace();
				}
				
				try
				{
					while(resultSet2.next())
					{
						int Sno = resultSet2.getInt("Sno");
						String name = resultSet2.getString("Sname");
						String Ssex = resultSet2.getString("Ssex");
						String Sdept = resultSet2.getString("Sdept");
						int Sage = resultSet2.getInt("Sage");
						date_string2[k++] = "學號:" + Sno + ",姓名:" +name + ",性別:" + 
								Ssex + ",年齡:" + Sage + "歲,專業:" + Sdept;
						
					}
					resultSet2.close();
				}catch(SQLException q)
				{
					q.printStackTrace();
				}finally {
						try {
							statement.close();
						} catch (SQLException e2) {
							
							e2.printStackTrace();
						}
						try {
							connection.close();
						} catch (SQLException e2) {
							
							e2.printStackTrace();
						}
					}
					
					Change aa = new Change();
					aa.setVisible(true);
					temp[1].setText("查詢成功");
					aa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				}
				k = 0;
			}
        	
        });
       
        
        getContentPane().setLayout(new BorderLayout(3, 2));
        if(k > 0) {
        	getContentPane().add("North" , date1);	
        }else
        	getContentPane().add("North" , date);		
        getContentPane().add("Center" , use);
        getContentPane().add("South" , input);
        use.setPreferredSize(new Dimension(0 , 20));
        input.setPreferredSize(new Dimension(0,80));
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Change a = new Change();
		a.setVisible(true);
		a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
	}

}

感謝閱讀

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