1. 程式人生 > >eclipse中與資料庫的建立,將資料庫表在介面上顯示,以及實現資料表的增刪改查操作

eclipse中與資料庫的建立,將資料庫表在介面上顯示,以及實現資料表的增刪改查操作

首先前期工作這裡就不講了,比如說資料庫的建立,MySql連線驅動等內容。

介面主要內容:

(1)執行出現第一個點選按鍵,點選後進入JTable資料繫結例項介面

(2)接下來就可以進行相應操作。

廢話不說,直接上效果圖。

圖一 新增資料前


圖二 新增資料後


圖三 修改資料後


圖四 刪除資料前


圖五 刪除資料後

下面是程式碼:

test11.java檔案:

package test11;
import java.sql.*;

import javax.swing.JTable;

public class test11 {

    /*public static void main(String[] args) {
        try {
            /*Class.forName("com.mysql.jdbc.Driver");//載入資料庫驅動
            System.out.println("載入資料庫驅動成功");
            String url="jdbc:mysql://localhost:3306/qwert";//宣告資料庫test的url
            String user="root";//資料庫的使用者名稱
            String password="d";//資料庫的密碼
            //建立資料庫連線,獲得連線物件conn(丟擲異常即可)
            Connection conn=DriverManager.getConnection(url, user, password);
            System.out.println("連線資料庫成功");
          //生成一條mysql語句
            //String sql="insert into personInfo(personId,name,gender,age) values('1001','xiaoong','male',23)";        
             Statement stmt=conn.createStatement();//建立一個Statement物件
            //stmt.executeUpdate(sql);//執行sql語句
            //System.out.println("插入到資料庫成功");
            //conn.close();
            //System.out.println("關閉資料庫成功");
            String sql1 = "select * from personInfo";    //要執行的SQL
            ResultSet rs = stmt.executeQuery(sql1);//建立資料物件
                System.out.println("編號"+"\t\t"+"姓名"+"\t\t"+"性別"+"\t\t"+"年齡");
                while (rs.next()){
                    System.out.printf("%-16s",rs.getInt(1));
                    System.out.printf("%-16s",rs.getString(2));
                    System.out.printf("%-16s",rs.getString(3));
                    System.out.printf("%-16s",rs.getString(4));
                    System.out.println();
                }
                rs.close();
                String sql2="update personInfo set gender = 'female' where personId = 1002";
                stmt.executeUpdate(sql2);//執行sql語句
                String sql3="update personInfo set name = 'xiao' where personId = 1002";
                stmt.executeUpdate(sql3);//執行sql語句
                String sql4="delete from personInfo where age = 21";
                stmt.executeUpdate(sql4);//執行sql語句
        	
        	
        	Connection conn1 = fun1();
        	Statement stmt=conn1.createStatement();//建立一個Statement物件
        	fun2(conn1);
        	fun3(conn1);
        	
            stmt.close();
            
            conn1.close();
        } 
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/
    public static Connection fun1() {
    	Connection conn = null;
    	try {
            Class.forName("com.mysql.jdbc.Driver");//載入資料庫驅動
            System.out.println("載入資料庫驅動成功");
            String url="jdbc:mysql://localhost:3306/qwert?useUnicode=true&characterEncoding=utf-8";//宣告資料庫test的url
                               //?useUnicode=true&characterEncoding=utf-8作用是可以成功的把漢字的資料傳輸到文字中
            String user="root";//資料庫的使用者名稱
            String password="d";//資料庫的密碼
            //建立資料庫連線,獲得連線物件conn(丟擲異常即可)
            conn=DriverManager.getConnection(url, user, password);
            System.out.println("連線資料庫成功");
    	} catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
        	e.printStackTrace();
        }//
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }	
    	return conn;
    }
    public static int i=1;
    public static void fun2(Connection conn,String sql) {        //fun2作用是向資料庫中插入同類型資料
    	      
        try
		{
			Statement stmt=conn.createStatement();//建立一個Statement物件
			stmt.executeUpdate(sql);//執行sql語句
		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       System.out.println("插入到資料庫成功");
    	
    }
    
    public static Object[][] fun3(Connection conn) throws SQLException {
    	String sql = "select * from personInfo";   
    	java.sql.PreparedStatement pstm =null;
		try
		{
			pstm = conn.prepareStatement(sql);
		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
    	// 執行查詢  
    	ResultSet rs = pstm.executeQuery();  
    	// 計算有多少條記錄  
    	int count = 0;  
    	while(rs.next()){  
    	count++;  
    	}  
    	rs = pstm.executeQuery();  
    	// 將查詢獲得的記錄資料,轉換成適合生成JTable的資料形式  
    	Object[][] info = new Object[count][4];  
    	count = 0;  
    	while(rs.next()){  
    	info[count][0] = Integer.valueOf( rs.getInt("personId"));  
    	info[count][1] = rs.getString("name");  
    	info[count][2] = Integer.valueOf( rs.getInt("age") );  
    	info[count][3] = rs.getString("gender");  
    	count++;  
    	}  
    	
    	// 定義表頭  
    	// 建立JTable 
    	return info;
    	  
    }
    
    public static void fun4(Connection conn,String sql4) {
    	
		try
		{
			Statement stmt = conn.createStatement();
			//String sql2="update personInfo set gender = 'female' where personId = 1012";
	        stmt.executeUpdate(sql4);//執行sql語句
		} catch (SQLException e)
		{
			
			e.printStackTrace();
		}	
		System.out.println("修改到資料庫成功");
    }
    
    public static void fun5(Connection conn,String sql5) {
    	
		try
		{
			Statement stmt = conn.createStatement();
			//String sql4="delete from personInfo where gender = female";
            stmt.executeUpdate(sql5);//執行sql語句
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("刪除到資料庫成功");	
    }
}

jiemian11.java檔案

package test11;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.JTableHeader;



public class jiemian11 extends JFrame
{

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args)
	{
		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				try
				{
					jiemian11 frame = new jiemian11();
					frame.setVisible(true);
					
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * Create the frame.
	 */

	public jiemian11()
	{
		super("學生資訊管理系統");
		JPanel contentPane = new JPanel();
		this.setBounds(100, 100, 450, 300);
		//setBounds(x,y,width,height); x:元件在容器X軸上的起點 y:元件在容器Y軸上的起點 width:元件的長度 height:元件的高度
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		JButton b1 = new JButton("點選");
		contentPane.add(b1, BorderLayout.CENTER);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		b1.addActionListener(new ActionListener(){         //b1按鈕的點選事件
			public void actionPerformed(ActionEvent arg0) {
//這裡就是偵聽後觸發事件處理的程式碼部分
//比如說你要觸發的另一個class類名為NewWindow,是繼承自JFrame的窗體class
//那麼如下程式碼就可以了
				//test11 t1= new test11();
				//Connection conn1 = (Connection) t1.fun1();
				//t1.fun3(conn1);
				test frame1 = new test();
				frame1.setVisible(true);
//這樣就實現該按鈕觸發新的class程式NewWindow了
          }
		});
	}
}
class test extends JFrame{  
	// 定義元件  
	private JScrollPane scpDemo;  
	private JTableHeader jth;  
	private JTable tabDemo;  
	private JButton btnShow,b2,b3,b4; 
	private TextField text1,text2,text3;
	// 構造方法  
	public test(){  
	// 窗體的相關屬性的定義  
	super("JTable資料繫結示例");  
	this.setSize(600,400);  
	this.setLayout(null);  
	this.setLocation(300,40);  
	// 建立元件  
	this.scpDemo = new JScrollPane();  
	this.scpDemo.setBounds(20,50,560,300); 
	this.btnShow = new JButton("顯示資料"); 
	text1 = new TextField();
	text2 = new TextField();
	text3 = new TextField();
	b2 = new JButton("新增資料");
	b3 = new JButton("修改資料");
	b4 = new JButton("刪除資料");
	b2.setBounds(165, 10, 125, 30);
	b3.setBounds(310, 10, 125, 30);
	b4.setBounds(455, 10, 125, 30);
	this.btnShow.setBounds(20,10,125,30);  
	// 給按鈕註冊監聽  
	this.btnShow.addActionListener(new ActionListener(){  
	public void actionPerformed(ActionEvent ae){  
	try
	{
		btnShow_ActionPerformed1(ae);
	} catch (ClassNotFoundException e)
	{
		// TODO Auto-generated catch block
		e.printStackTrace();
	}  
	}  
	});  
	
	b2.addActionListener(new ActionListener(){           //按鈕的點選事件
		public void actionPerformed(ActionEvent ae){  
		btnShow_ActionPerformed2(ae);  
		}  
		});
	
	b3.addActionListener(new ActionListener(){  
		public void actionPerformed(ActionEvent ae){  
		btnShow_ActionPerformed3(ae);  
		}  
		});
	
	b4.addActionListener(new ActionListener(){  
		public void actionPerformed(ActionEvent ae){  
		btnShow_ActionPerformed4(ae);  
		}  
		});
	// 將元件加入到窗體中  
	add(this.scpDemo);  
	add(this.btnShow);
	add(b2);
	add(b3);
	add(b4);
	// 顯示窗體  
	this.setVisible(true);  
	}  
	test11 t1= new test11();
	java.sql.Connection conn = t1.fun1();
	// 點選按鈕時的事件處理  
	public void btnShow_ActionPerformed1(ActionEvent ae) throws ClassNotFoundException{  
	    
	try{    
		//java.sql.Connection conn = t1.fun1();
	{
		Object[][] info = test11.fun3(conn);       //將資料庫資料轉換為jtable表
		// 定義表頭  
		String[] title = {"學號","姓名","年齡","性別"};  
		// 建立JTable  
		this.tabDemo = new JTable(info,title);  
		// 顯示錶頭  
		this.jth = this.tabDemo.getTableHeader();  
		// 將JTable加入到帶滾動條的面板中  
		this.scpDemo.getViewport().add(tabDemo);  
	}
	}catch(SQLException sqle){  
	JOptionPane.showMessageDialog(null,"資料操作錯誤","錯誤",JOptionPane.ERROR_MESSAGE);  
	}
	//catch(ClassNotFoundException cnfe){  
		//JOptionPane.showMessageDialog(null,"資料來源錯誤","錯誤",JOptionPane.ERROR_MESSAGE);    
	//} 
	}
	
	public void btnShow_ActionPerformed2(ActionEvent ae) {
		JDialog jd = new JDialog();
        jd.setBounds(320, 180, 600, 300);
        jd.setTitle("彈出文字框");
		text1.setBounds(20,50,560,300);
		jd.add(text1);
		jd.setModal(true);//確保彈出的視窗在其他視窗前面
        jd.setVisible(true);
        String gm = text1.getText();
		t1.fun2(conn,gm);      //向資料表中新增資料
		//text1.setText("");
		
	}
	
	public void btnShow_ActionPerformed3(ActionEvent ae) {
		JDialog jd = new JDialog();
        jd.setBounds(400, 220, 600, 300);
        jd.setTitle("彈出文字框");
		text2.setBounds(20,50,560,300);
		jd.add(text2);
		jd.setModal(true);//確保彈出的視窗在其他視窗前面
        jd.setVisible(true);
        String gm = text2.getText();
		t1.fun4(conn,gm);        //將資料表中資料進行修改
		//text2.setText("");
		
	}
	
	public void btnShow_ActionPerformed4(ActionEvent ae) {
		JDialog jd = new JDialog();
        jd.setBounds(4800, 260, 600, 300);
        jd.setTitle("彈出文字框");
		text3.setBounds(20,50,560,300);
		jd.add(text3);
		jd.setModal(true);//確保彈出的視窗在其他視窗前面
        jd.setVisible(true);
        String gm = text3.getText();
		t1.fun5(conn,gm);         //將資料表中資料進行刪除
		//text3.setText("");
		
	}
}

總結,花了兩天時間,逛了眾多大佬的部落格,終於寫出來了。。。


恩,這就是我想說的。