Table-based output of query results in Java Database Programming

Source: Internet
Author: User
Tags sybase sybase database
When developing a database application system using Java, you often need to display the query results on the user interface. Since the jdk1.x Development Kit provided by Sun is not a visual integrated development environment (IDE), the query results cannot be conveniently displayed in tables such as DBGrid as Delphi and VB. Therefore, you can only write your own code.
In practical applications, we can use vector, jtable, and abstracttablemodel to better solve this problem. The following describes the implementation methods in detail.

1. Introduction to class vector, class jtable and class abstracttablemodel:

1. Vector:
The class vector is a collection class of Java history and belongs to the java. util package. It encapsulates heterogeneous linked lists and arrays. It has the following two features:
* The vectors are heterogeneous and do not require the same type of each element. The vectors can be mixed with Multiple object types;
* Vectors are arrays, because they can dynamically increase when adding elements.
Its Heterogeneity is in line with the characteristics of different attribute types in database records, and its dynamic nature is also in line with the characteristics of the number of results set records in database queries.
The class vector is defined as follows:
Public class vector extends actlist
Implements list, cloneable, serializable {...}
It allows you to search, add, and delete vector members. For example, add (Object OBJ) can easily add an object; get (INT index) can easily get an object in the vector; remove (Object OBJ) you can easily delete an object in a vector.

2. jtable class:
The jtable component is a complex small component in the swing component and is affiliated to the javax. Swing package. It can display data in the form of a two-dimensional table. The jtable class is defined as follows:
Public class jtable extends jcomponent
Implements tablemodellistener, scrollable, tablecolumnmodellistener,
Listselectionlistener, celleditorlistener, accessible {...}
Jtable has the following features when displaying data:
* Customization: You can customize the display mode and editing status of data;
* Heterogeneous: different types of data objects can be displayed, including complex objects such as colors and icons;
* Simplicity: You can easily create an external table by default.
Customization can meet the requirements of different users and scenarios, and the heterogeneity is also in line with the characteristics of different attribute types in the database access result set. Jtable-like provides rich two-dimensional table operation methods, such as setting the editing status, display mode, and selecting columns.
Before using jtable to display data, you must generate a custom model, cell Paster, or cell editor as needed. The abstractlistmodel class is used to customize your own data models. This class will be introduced later. The tablecellrenderer interface is used to customize the cell Paster, And the tablecelleditor interface is used to customize the cell editor. These two interfaces are mainly used to process color objects. They are not used in the example and are not described too much.

3. Class abstracttablemodel:
The class abstracttablemodel is an abstract class that is not fully implemented and cannot be instantiated. It must be implemented in a program. It is affiliated with javax. Swing. Table. The class is defined as follows:
Public abstract class extends acttablemodel extends object
Implements tablemodel, serializable {...}
Class abstracttablemodel provides the default implementation of most methods in the tablemodel interface. The tablemodel interface defines the basic data structure of jtable. To generate your own data model, you can implement all the methods in the tablemodel interface to meet the requirements. However, the function of managing the audience table is common for all data models, so in javax. swing. the table also defines the class 'acttablemodel' to process this job. It not only manages the audience table, but also facilitates generating and entrusting tablemodelevents events to the audience.
To generate a specific tablemodel as a subclass of abstracttablemode, you must at least implement the following three methods:
Public int getrowcount ();
Public int getcolumncount ();
Public object getvalueat (INT row, int column );
So far, we can create a simple sequence table (5 × 5). the implementation method is as follows:
Tablemodel datamodel = 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 (datamodel );
Jscrollpane scrollpane = new jscrollpane (table );
II. Introduction to databases and their connection methods:
The example uses the Sybase Database System and stores the data inventory on the database server. Path: D:/worker, Database Name: worker. DBF. Has the following fields:
Field name
Type
Wno (employee ID)
Varchar
Wname (employee name)
Varchar
Sex)
Varchar
Birthday (date of birth)
Date
Wage (salary)
Float
To connect to the database, use the drivermanager class in the Java. SQL package. This is a utility class used to manage JDBC drivers. It provides methods such as getting a connection, registering a connection, revoking a driver, and setting a login timeout for registration and database access. The connection method is as follows:
Step 1: locate, mount, and link the sybdriver class;
Driver = "com. Sybase. JDBC. sybdriver ";
Sybdriver = (sybdriver) class. forname (driver). newinstance ();
Step 2: register the sybdriver class;
Drivermanager. registerdriver (sybdriver );
Step 3: Get the reference of the sybconnection object.
User = "sa ";
Password = "";
Url = "JDBC: Sybase: TDS: 202.117.203.114: 5000/worker ";
Sybconnection connection = (sybconnection) drivermanager. getconnection
(URL, user, password );
After the connection is established, You can query and change the database through the statement interface.

Iii. Implementation Method:
Only the core code is provided here. The package introduction, interface processing, variable definition, and other sections are not described.
Step 1: Object declaration.
Abstracttablemodel TM; // declare an acttablemodel object
Jtable jg_table; // declare a class jtable object
Vector vect; // declare a vector object
Jscrollpane JSP; // declare a scroll bar object
String title [] = {"employee ID", "employee name", "gender", "Date of Birth", "salary "};
// Column name of the tables Table
Step 2: create a custom table.
1. Implement the methods in the TM object of the abstract class abstracttablemodel:
Vect = new vector (); // instantiate a vector
TM = new abstracttablemodel (){
Public int getcolumncount (){
Return title. length;} // obtain the number of columns in the table.
Public int getrowcount (){
Return vect. Size ();} // obtain the number of rows in the table
Public object getvalueat (INT row, int column ){
If (! Vect. isempty ())
Return
(Vector) vect. elementat (ROW). elementat (column );
Else
Return NULL;} // get the attribute value in the cell
Public String getcolumnname (INT column ){
Return title [column];} // sets the table column name.
Public void setvalueat (object value, int row, int column ){}
// The data model cannot be edited. This method is set to null.
Public class getcolumnclass (INT c ){
Return getvalueat (0, c). getclass ();
} // Obtain the object class of the column
Public Boolean iscelleditable (INT row, int column ){
Return false;} // sets the cell to be uneditable, which is implemented by default.
};
2. Create a custom table:
Jg_table = new jtable (TM); // generate your own data model
Jg_table.settooltiptext ("show all query results"); // sets the help prompt
Jg_table.setautoresizemode (jtable. auto_resize_off );
// Set the table size adjustment mode
Jg_table.setcellselectionenabled (false); // sets the cell selection method.
Jg_table.setshowverticallines (true); // you can specify whether to display the split lines 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 to the database: the second part is provided.
2. database query:
Statement stmt = connection. createstatement ();
Resultset rs1_stmt.exe cutequery ("select * from worker ");
3. display query results:
Vect. removeallelements (); // initialize the vector object
TM. firetablestructurechanged (); // update table content
While (Rs. Next ()){
Vector rec_vector = new vector ();
// Extract data from the result set and put it into the vector rec_vector
Rec_vector.addelement (Rs. getstring (1 ));
Rec_vector.addelement (Rs. getstring (2 ));
Rec_vector.addelement (Rs. getstring (3 ));
Rec_vector.addelement (Rs. getdate (4 ));
Rec_vector.addelement (new float (Rs. getfloat (5 )));
Vect. addelement (rec_vector); // The vector rec_vector is added to the vector vect.
}
TM. firetablestructurechanged (); // update the table to display the content of the vector vect.
The example is as follows:

There are two methods to achieve the effect of record flip and flip in the graph:
1. If the software environment supports jdbc2.0, you can directly use Rs. prevoius () and Rs. next () to obtain the record, and then display the values of each field through the settext () method in the jtextfield class.
2. If jdbc2.0 is not supported, you can use the vector to extract data from jtable by row. Customizes a pointer to record positions. When the pointer is added to 1, the previous row of data is taken and put into the vector for display. When the pointer is reduced to 1, the next row of data is taken for display. The display method is the same as above.
Note: The Code does not provide any exception for capturing, such as sqlexception, which must be provided in actual applications. In addition, in some systems, Chinese characters in text fields may not be correctly displayed and must be implemented using other methods.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.