Hiển thị các record dữ liệu từ cơ sở dữ liệu

Hầu hết các thông tin cần tổ chức dưới dạng bảng đều được lấy từ các cơ sờ dữ liệu quan hệ. Nếu ta phát triển những chương trình ứng dụng chuyên nghiệp thì có thể sử dụng Java Bean (được đề cập ờ chương sau) để truy cập vào CSDL để lấy thông tin dưới dạng các record.

Ví dụ 4.7. Đơn giản hơn, ta có thể sử dụng cơ chế kết nối JDBC [1] để truy vấn vào một CSDL và hiển thị kết quả dưới dạng các bảng.

Trước tiên ta định nghĩa ResultSetTableModel để tồ chức dừ liệu kết quả thu được từ truy vấn vào một CSDL.

Ta có thể biết được số cột, tèn các cột từ đối tượng siêu dừ liệu kết quả:

public int getColumnCount(){ try {

return rsmd.getColumnCount();

}catch(SQLException e){

System.out.println(“Error:  ” +- e);

return 0;

public String getColumnName(int c){ try (

return rsmd.getColumnName (c + 1);

}catch(SQLException e){

System.out.println(“Error: ” + e); return

Chương trình truy vấn vào một CSDL và hiển thị kết quà dưới dạng bảng được viết như

// Result SetTable. java

import j ava.awt.*; import j ava.awt.event.*; import j ava.sql.*; import java.Util.*; import j avax.swing.*;

import javax.swing.table; public class ResultSetTable{

public static void main(String args[]){

JFrame fr = new ResultSetTableFrame(); fr.show();

}

}

class ResultSetTableFrame extends JFrame implements

ActionListener { private JScrollPane scrollPane; private ResultSetTableModel model; private JComboBox tableNames; private JButton nextButton; private JButton previousButton; private ResultSet rs; private Connection con; private Statement stmt;

private static boolean SCROLLABLE = false;

public ResultSetTableFrame(){

setTitle(“Result Set Table”); setSize(300, 200);

addWindowListener(new WindowAdapter(){

public void windowclosing(WindowEvent e){ System.exit(0);

}

}) ;

// Tim tất cả các bảng trong CSDL và đưa vào hộp Combo Box

Container content = getContentPane(); tableNames = new JComboBox(); tableNames.addActìonLìstener(this);

JPanel p = new JPanel(); p . add(tableNames);

content.add(p, “North”); try {

Class.forName(“com.pointbase.jdbc.JdbcDriver”); // Nạp Driver

String url = “jdbc:pointbase:corejava”; String user = “PUBLIC”;

String pw = “PUBLIC”;

con = DriverManager.getConnection(url, user, pw); if (SCROLLABLE)

stmt = con.createStatement

(ResultSet.TYPE_SCROLL_INSEN SITIVE, Re suitSet.CONCUR_READ_ONLY);

else

stmt = con.createstatement(); DatabaseMetaData md = con.getMetaData(); ResultSet mrs = md.getTables(null, null, null, new String[] { “TABLE”

}) ;

while(mrs.next())

tableNames.addltem(mrs.getstring (3)); mrs.close ();

}catch(ClassNotFoundException e){

System.out.println(„Error: „ + e);

}

catch(SQLException e){

System.out.println(“Error: ” + ej ;

}

}

public void actionPerformed(ActionEvent evt){ if(evt.getSource() == tableNames){

// Hiển thị bảng đã được chọn trong bảng Combo Box if (scrollPane != null)

getContentPane().remove(scrollPane);

try {

String tableName

= (String)tableNames.getSelectedltem(); if(rs ! = null) rs.close ();

String query = “SELECT * FROM ” + tableName; if(SCROLLABLE)

model = new ScrollResultSetTableModel(rs); else

model = new CachingResultSetTableModel(rs); JTable table = new JTable(model); scrollPane = new JScrollPane(table); getContentPane () .add(scrollPane, “Center”) pack() ; doLayout();

}catch(SQLException e){

System.out.println(“Error: ” + e);

}

}

}

}

// Lớp cơ sờ để điều chinh việc cuộn dữ liệu và cất giữ mô hình bảng của tập kết quả

abstract class ResultSetTableModel extends

AbstractTableModel{ private ResultSet rs; private ResultSetMetaData rsmd;

public ResultSetTableModel(ResultSet aRes){ rs = aRes; try { .

rsmd = rs.getMetaData();

)catch(SQLException e){

System.out.println(“Error:               ” + e);

public ỉnt getColumnCount(){ try {

return rsmd.getColumnCount();

}catch(SQLExceptíon e){

System.out.println{“Error: ” + e); return 0;

}

}

public ResultSet getResultSet(){ return rs;

)

public String getColumnName(int c) { try {

return rsmd.getColumnName(c + 1);

}catch(SQLException e){

System.out.println(“Error: ” + e); return “”;

}

}

}

// Lớp sử dụng con trỏ cuộn dữ liệu có ở JDBC 2

class ScrollResultSetTableModel extends

ResultSetTableModel{

public ScrollResultSetTableModel(ResultSet aRes){ super(aRes);

}

public Object getValueAt(int r, int c){ try {

ResultSet rs = getResultSet();

rs.absolute(r + 1) ;

return rs.getobject(c + 1);

}catch (SQLException e){

System.out.println(“Error: ” + e);

return null;

}

}

public int getRowCount(){ try {

ResultSet rs = getResultSet() ;

rs .last();

return rs.getRowO;

}catch(SQLException e)[

System.out.println(“Error:               ” + e);

return D;

}

}

}

// Lớp cất giữ dữ liệu kết quả

class CachingResultSetTableModel extends

ResultSetTableModel{

public CachingResultSetTableModel(ResultSet aRes){ super(aRes) ; try {

cache = new ArrayListO; int cols = getColưmnCount();

ResultSet rs = getResultSet();

// Tim các bản ghi tiếp theo while(rs.next()){

Object[] row = new Object[cols]; for(int j = 0; j < row.length; j++) row[j] = rs.getobject (j + 1); cache.add(row);

}

}catch(SQLException e){

System.out.printlr'”Error:                ” + e);

}

}

public Object getValueAt(int r, int c){ if(r < cache.size())

return ((Object[])cache.get(r))[c];

else

return null;

}

public int getRowCount(){
return cache.size 0;

}

private ArrayList cache;

}