2012年11月17日 星期六

Java 實作JTable及取JTable欄位值等

本篇簡單實作JTable以及如何取得JTable欄位值,如有補充會再加上。
如果有需要請自行複製程式碼,自行修改!!

(一)前置準備:
1.需有資料庫mysql
2.需要有Java JDBC資料庫的驅動
   (不會作請自行參考JAVA安裝MySQL驅動程式)

(二)實作:
test_db.java
test.java

(三)程式碼如下:
不懂看註解,再不懂請自行查資料、翻翻手邊的書吧!!
test_db.java:

import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class test_db {

private Connection con = null; //Database objects
//連接object
private Statement stat = null;
//儲存sql執行的結果
private ResultSet rs = null;
ResultSetMetaData rsmd;
private PreparedStatement pst = null;
JTable New_DJT;//儲存資料用
    public test_db() {
    }
 
    //開啟連結
public int jdbcmysql() {
   try {
    Class.forName("com.mysql.jdbc.Driver");
   //註冊driver
   con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","test","test");
   //"jdbc:mysql://localhost:3306/test"
   // localhost 是主機名稱,3306是mysql資料庫port(自己看自己的電腦mysql資料庫的port為多少),test 是資料庫名稱,test是帳號,root 是密碼,con 是取得連線
   return 1;
   }
   catch(ClassNotFoundException e)
   {
     System.out.println("DriverClassNotFound :"+e.toString());
     return -1;
   }//有可能會產生sqlexception
   catch(SQLException x) {
     System.out.println("Exception :"+x.toString());
     return 0;
   }

    }
 
    //Select Table Data
    //YND是0只單存判斷是否有資料,如果是1代表判斷是否有資料並且要取資料
    public int STD(String selectSQL,int YND){
    try{
   
stat = (Statement) con.createStatement();
rs = stat.executeQuery(selectSQL); //executeQuery()執行sql指令
rs.last(); //將游標移到最後一筆資料
int ResultCount = rs.getRow(); //rs.getRow()取得資料列,找不到資料會是0 有資料會>=1
rs.beforeFirst(); //回到第一個ResultSet

//假如判斷是否有資料並且取資料
if (ResultCount>=1 && YND==1){

rsmd = rs.getMetaData(); //取得中介資料,如資料庫的欄位名稱.欄位數.欄位型態等
int cx=rsmd.getColumnCount();//取得欄位數
System.out.println(cx);

//參考資料:http://www.interinfo.com.tw/edoc/ch20/frontline.htm
//Vector是一種能夠自動長大或縮小的陣列形態,其最大的用途就是彌補Array 的彈性不足,在宣告的時後,可以不必宣告其大小,等到物件一個個的加入時,容量不足時就會自動加大容量。
Vector V_CNames=new Vector();//表頭名稱
for(int x=1;cx>=x;x++){
//設定表頭名稱
V_CNames.addElement(("x"+String.valueOf(x)));
}

Vector V_RData=new Vector();//儲存資料庫撈出來的所有資料列
while(rs.next()){
Vector New_RD=new Vector();
for(int x=1;cx>=x;x++){
//rs.getString(數值)取得rs中的值,並丟入New_DR,形成一行資料列
New_RD.addElement(rs.getString(x));
}
V_RData.addElement(New_RD);//New_RD加入到V_RData
}
//New_DJT=new JTable(資料列,表頭);
New_DJT=new JTable(V_RData,V_CNames);
JScrollPane jsp;//宣告一個滾動槓(捲動容器)
New_DJT.setShowVerticalLines(true);//設定是否顯示表格的垂直分割線
New_DJT.setShowHorizontalLines(true);//設定是否顯示表格的水平分割線
jsp=new JScrollPane(New_DJT);//給JTabel表格加上滾動槓(捲動容器)

JFrame myFrame=new JFrame("取得資料庫表格測試");
myFrame.setSize(500,200);
myFrame.setLocation(200,200);
// 把 table 放進JFrame
myFrame.getContentPane().add(jsp);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//=============================
int row=New_DJT.getRowCount(); //取得列數
       int col=New_DJT.getColumnCount();  //取得行數
       System.out.println("col欄位數:"+col+"; row列數:"+row);
         
           for(int i=0;row>i;i++){
            for(int j=0;col>j;j++){
            if (j==(col-1)){
            //印出值並換行
            System.out.println((String)New_DJT.getValueAt(i, j)); //取得JTable中的值強制轉換String型態
            }else{
            //印出值並不換行
            System.out.print((String)New_DJT.getValueAt(i, j)+" | ");
            }
            }
           }

}else{
//判斷是否有資料

}
return 1;
    }catch(SQLException e){
System.out.println("DropDB Exception :" + e.toString());
return -1;//發生錯誤及異常
/**}finally{
Close();
System.out.println("Close");*/
   }
//int ResultCount = rs.getRow();
    }
public void Close() {
 try
 {
   if(rs!=null)
   {
     rs.close();
     rs = null;
   }
   if(stat!=null)
   {
     stat.close();
     stat = null;
   }
   if(pst!=null)
   {
     pst.close();
     pst = null;
   }
 }
 catch(SQLException e)
 {
   System.out.println("Close Exception :" + e.toString());
 }
}
}


test.java:

public class test {

    public test() {
    }
    public static void main(String[] args){
    //test_wf TWF=new test_wf();
    test_db t_db=new test_db();
    if (t_db.jdbcmysql()==1){
    System.out.println("1");
    //t_db.STD(sql指令字串,1) 1代表取資料
if(t_db.STD("SELECT * FROM test1",1)==1){
System.out.println("2");
t_db.Close(); //關閉資料庫所有資源
}
    }

    }
}

結果如下: