Current location - Recipe Complete Network - Complete cookbook of home-style dishes - How to display query results in tables with java
How to display query results in tables with java
When developing a database application system with Java, it is often necessary to display the query results on the user interface. Because the JDK 1.x development package provided by SUN Company is not a visual integrated development environment (IDE), it is impossible to display the query results in DBGrid and other tables as easily as Delphi and VB. So you can only do it by writing your own code.

In practical application, we can use Vector, JTable and AbstractTableModel to solve this problem. Below, introduce the implementation method in detail.

I introduction of class Vector, class JTable and class AbstractTableModel:

1, category vector:

Class Vector is a historical collection class of Java and belongs to the java.util package. It wraps heterogeneous linked list and array mixture, and has the following two characteristics:

* Vector is heterogeneous, and each element is not required to have the same type, and various object types can be mixed in the vector;

* Vector is a mixture of arrays, because they can be dynamically increased when adding elements.

Its heterogeneity is consistent with the characteristics of different attribute types in database records, and its dynamics is consistent with the characteristics of uncertain number of result set records in database queries.

The category vector is defined as follows:

Common class vector extended abstract list

Implementation list, which can be cloned and serialized.

The method of finding, adding and deleting vector members is realized. For example, add(Object obj) can easily add an object; Get(int index) can easily get an object in the vector; Remove (object object). You can easily delete objects in a vector.

2.JTable class:

JTable component is a relatively complex widget in Swing component, which belongs to javax.swing package and can display data in the form of two-dimensional table. The JTable class is defined as follows:

The public class JTable extends JComponent.

Implement TableModelListener, Scrollable, TableColumnModelListener,

ListSelectionListener, CellEditorListener, available at {…}

JTable class has the following characteristics when displaying data:

Customizability: you can customize the display mode and editing status of data;

* Heterogeneity: different types of data objects can be displayed, even including complex objects such as colors and icons;

* Simplicity: By default, you can easily set up a two-dimensional table.

Its customization can meet the needs of different users and occasions, and its heterogeneity coincides with the characteristics of different attribute types in the database access result set. The JTable class provides extremely rich methods for manipulating two-dimensional tables, such as setting compilation.

Series status, display mode, grade selection, etc. I won't go into details here.

Before using JTable class to display data, you must generate a custom model, unit painter or unit editor according to the situation. Class AbstractListModel is used to customize the user's own data model, which will be introduced later.

TableCellRenderer interface is used to customize the cell renderer, and TableCellEditor interface is used to customize the cell editor. These two interfaces are mainly used to process color objects, which are not used in the example and will not be explained too much.

3. class AbstractTableModel:

Class AbstractTableModel is an abstract class, which is not fully implemented and cannot be instantiated. When using it, the method must be implemented in the program. It belongs to the javax.swing.table class and is defined as follows:

Public abstract class AbstractTableModel extension object

Implement TableModel, Serializable{…}

The AbstractTableModel class provides the default implementation of most methods in the TableModel interface. The TableModel interface defines the basic data structure of JTable. Users want to generate their own data models, which could have been done.

All methods in the TableModel interface are implemented to meet the requirements, but the function of managing the audience table is common to all data models, so the AbstractTableModel class is defined in javax.swing.table

Take care of this job. It not only manages the audience table, but also helps to generate TableModelEvents events and delegate them to the audience.

To generate a concrete TableMode as a subclass of AbstractTableMode, at least the following three methods must be implemented:

public int getRowCount();

public int getColumnCount();

Public object getValueAt(int row, int column);

At this point, we can build a simple two-dimensional table (5×5), and the implementation method is as follows:

table model data model = new AbstractTableModel(){

public int getColumnCount(){ return 5; }

public int getRowCount(){ return 5; }

public Object getValueAt(int row,int col){ return new Integer(row * col); }

};

JTable table = new JTable(data model);

JScrollPane scroll pane = new JScrollPane(table);

Second, the database and its connection method:

This example uses Sybase database system, and the database is stored in the database server. The path is: D:/WORKER, the database name is: worker.dbf has the following fields:

field name

type

Employee number

Variable length string

Wname (employee name)

Variable length string

Sex (gender)

Variable length string

Birth (date of birth)

date

salary

flotage

To connect to this database, you need to use the class DriverManager in the java.sql package. This class is a utility class for managing JDBC drivers. It provides methods such as obtaining connection through driver, registering, canceling driver, setting registration and database access timeout. The specific connection method is as follows:

Step 1: locate, load and link the SybDriver class;

driver = " com . Sybase . JDBC . syb driver ";

syb driver syb driver =(syb driver)class . for name(driver)。 new instance();

Step 2: register the SybDriver class;

driver manager . register driver(syb driver);

Step 3: get the SybConnection object reference.

user = " sa

Password = "";

URL = " JDBC:Sybase:Tds:202. 1 17 . 203 . 1 14:5000/WORKER ";

syb connection connection =(syb connection)driver manager . get connection

(Website, user, password);

After the connection is established, you can query and change the database through the statement interface.

Third, the implementation method:

Limited by space, only the core code is given here, and package introduction, interface processing, variable definition and other parts are not introduced.

Step 1: Object declaration.

AbstractTableModel tm// declares an abstracttablemodel object.

JTable jg _ table// Declares an object similar to JTable.

Vector//Declares a vector object.

JScrollPane jsp// Declares a scroll bar object.

String title[]={ Employee Number, Employee Name, Gender, Date of Birth, Salary};

//column name of 2D table

Step 2: Customize the form.

1. implementation method in AbstractTableModel object tm:

Vector = new vector (); //Instantiate the vector

tm=new AbstractTableModel(){

public int getColumnCount(){

Return title.length}// Get the number of rows in the table.

public int getRowCount(){

Returns vector.size (); }//Get the number of rows in the table

Common object getValueAt(int row, int column){

If (! vect.isEmpty())

return

((Vector)vect.elementAt(row))。 ElementAt (column);

other

Return null}// Get the property value in the cell.

Common string getColumnName(int column){

Return the title [column]; }//Set the table column name

public void setvalue at(Object value,int row,int column){}

//The data model cannot be edited. This method is set to null.

Public class getColumnClass(int c){

Returns getValueAt(0, c). getClass();

}//Get the object class to which the column belongs.

public boolean is celled table(int row,int column){

Returns false}// Setting the cell to non-editable is the default implementation.

};

2. Customize the form:

jg _ table = new JTable(TM); //Generate your own data model

Jg_table.setToolTipText ("show all query results"); //Set Help Tips

jg _ table . setautoresizemode(JTable。 AUTO _ RESIZE _ OFF);

//Set the table resizing mode

jg _ table . setcellselectionenabled(false); //Set the cell selection method

jg _ table . setshowverticallines(true); //Set whether to display the dividing line between cells.

jg _ table . setshowhorizontallines(true);

JSP = new JScrollPane(jg _ table); //Add a scroll bar to the table

Step 3: Display the query results.

1. Connect the database: give the second part.

2. Database query:

Statement stmt = connection.createstatement ();

ResultSet RS = stmt . execute query(" select * from worker ");

3. Display the query results:

vect . remove allements(); //Initialize the vector object

TM . firetablestructurechanged(); //Update the table contents

while(rs.next()){

Vector rec _ vector = newvector ();

//Take data from the result set and put it into the vector rec_vector.

rec _ vector . add element(RS . getstring( 1));

rec _ vector . add element(RS . getstring(2));

rec _ vector . add element(RS . getstring(3));

rec _ vector . add element(RS . getdate(4));

rec _ vector . add element(new Float(RS . get Float(5)));

vect . add element(rec _ vector); //vector rec_vector is added to the vector.

}

TM . firetablestructurechanged(); //Update the table to display the contents of vector vector.