Table format output of Query results in Java database programming

zhaozj2021-02-17  73

---- When developing a database application system using Java, you often need to display query results on the user interface. Since Sun's JDK1.x Development Kit is not a visualized integrated development environment (IDE), it is not easy to easily display the query results in a table in DBGRID. Therefore, you can only rely on your own code.

---- In practical applications, we can use three classes such as Vector, JTable, AbstractTableModel to better solve this problem. Here, in detail, implement the method.

---- One, class Vector, class JTABLE and class AbstractTableModel profile:

---- 1, class Vector:

---- Class Vector is a historical collection class of Java, belonging to the Java.util package. It has been packaged with heterogeneous layers and array hybrids, with the following two features:

---- (1) vector is heterogeneous, no requirement of each element, and a variety of object types can be mixed in the vector;

---- (2) vector is an array hybrid because they can be increased during increasing elements.

---- It is constantly in line with the characteristics of different types of property types in database records, and its dynamics are just in line with database queries, and the result set records a number of species.

---- Class Vector is as follows:

Public Class Vector Extends AbstractListImplements List, Cloneable, Serializable {...}

---- Implementing the search, new, deletion, etc. of vector members. Such as: add (object obj) can easily add an object; Get (int index) can easily get an object in the vector; Remove (Object Obj) can easily delete an object in the vector.

---- 2, class JTable:

---- JTable component is a complicated small piece in the Swing component, which is part of the javax.swing package, which can display data in a two-dimensional table. Class JTABLE is defined as follows:

Public Class JTable Extends JcomponentImPlements TableModellistener, Scrollable, TableColumnModelliStener, ListSelectionListener, CelleditorListener, Accessible {...}

---- Class JTABLE has the following features when displaying data:

---- (1) Constant: You can customize the display mode and editing status of data;

---- (2) Isomeric: You can display different types of data objects, even complex objects such as colors, icons;

---- (3) Simple: You can easily establish a two-dimensional table in a default.

---- Its customizable can meet different users and occasions, isomeric that is also in line with the characteristics of the attribute type of database access results. Class JTABLE provides an extremely rich two-dimensional table operation method, such as setting an editing state, display mode, selecting row column, etc., will not be described here.

---- Before using the class JTable display data, you must generate a custom model, a unit drawer, or unit editor according to the situation. Class ABSTRACTLISTMODEL is used to customize user's own data model, which is later described later. The TableCellRenderer interface is used to customize the unit drawer, the TableCelleditor interface is used to customize the unit editor, which is mainly used for the processing of color objects, and is not used in the example, not excessive description.

---- 3, class AbstractTableModel:

---- Class AbstractTableModel is an abstract class, not fully implemented, can not instantiate, implement methods in the program during use. It is part of javax.swing.table. Class definitions are as follows: Public Abstract Class AbstractTableModel Extends ObjectImPlements TableModel, Serializable {...}

---- Class AbstractTableModel provides the default implementation of most methods in the TableModel interface. The TableModel interface defines the basic data structure of the JTABLE. Users must generate their own data models, which can be met by implementing all the methods in the TableModel interface, but the function of the management listener is common for all data models, so the class AbstractTableModel is defined in javax.swing.table. This work. It manages the audience table and provides a convenience of generating TableModeEvents incidents and entrusting the audience.

---- To generate a specific TableModel as a subclass of AbstractTableMode, at least three methods must be achieved:

Public int getRowcount (); public int getColumncount (); public object getValueat (int Row, int column);

--- Here, we can build a simple two-dimensional 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, database and its connection method introduction:

---- Example Adopts the Sybase database system, data inventory is placed in the database server. The path is: d: / worker, the database name is: worker.dbf. Has the following fields:

Field name type WNO (employee) VARCHARWNAME (employee name) VARCHARSEX (gender) VARCHARBIRTHDAY (Birth Date) DateWage Float

---- To connect 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 connecting, registration, undo driver, setting registration, and database access login email. The specific connection method is as follows:

---- The first step: positioning, loading, and linking the Sybdriver class;

Driver = "com.sybase.jdbc.sybdriver"; sybdriver sybdriver = (sybdriver) class.forname (driver) .newinstance ();

---- Step 2: Register the SybDriver class;

Drivermanager.RegisterDriver (Sybdriver);

---- Step 3: A SybConnection object is acquired. User = "sa"; password = ""; url = "JDBC: SYBASE: TDS: 202.117.203.114: 5000 / wor"; SybConnection Connection = (SybConnection) DriverManager.getConnection (URL, User, Password);

---- After the connection is established, you can perform the query and change of the database via the Statement interface.

---- Third, implementation method:

---- Limited to the space, only the core code, the introduction, interface processing, and variable definitions, etc. are given. Step 1: Object declaration.

AbstractTableModelTM; // Declare a class AbstractTableModel object jtable jg_table; // Declare a class jtable object vector vect; // declare a vector object jscrollpane jsp; // Declare a rolling bar object string title [] = {"Workers", "Staff name", "gender", "date", "salary"}; // two-dimensional table name

---- Step 2: Custom form.

---- 1, the method in which the abstract class AbstractTableModel object TM is implemented:

Vect = new vector (); // Instantian TM = New AbstractTableModel () {public int getColumnCount () {return title.Length;} // get the table number PUBLIC INT GETROWCOUNT () {Return Vect.size (); } // Number of Public Object GetValueat (INT ROW, INT Column) {if (!). ELSERTURN NULL; ELSERTURN NULL; ELSERTURN NULL;} / / Acquired attribute values ​​in the cell PUBLIC STRING GETCOLUMNNAME (INT Column) {Return Title [Column];} // Setting Table Public Void SetValueat (Object Value, int Row, int column) {} // Data model is not editable This method is set to empty public class getColumnClass (int C) {return getValueat (0, c) .GetClass ();} // get the column belonging object class public boolean iscelleditable (int Row, int column) {Return False;} / / Set cells are not editable, for the default implementation};

---- 2, custom form:

Jg_table = new jtable (tm); // Generate its own data model JG_TABLE.SetTooltiptext ("Show all query results"); // Setting help prompt jg_table.setAutoResizeMode (jtable.auto_resize_off); // Set the table to adjust the size mode JG_TABLE. SetCellSelectionNableNabled (false); // Set cell selection mode JG_Table.SetShowVerticaline (TRUE); // Set whether to display the divided line JG_Table.SetShowhorizontallines (TRUE) (JSP = New JScrollpane) (JG_TABLE); // Give Form Strong bar

---- Step 3: Show the results of the query.

---- 1, connect the database: The second part has been given. ---- 2, database query:

St.createStatement (); ResultSet RS = Stmt.executeQuery ("SELECT * from worker");

---- 3, display query results:

Vect.removeAllelements (); // Initialization Vector Object TM.FireTablestructureChanged (); // Update Table Content While (rs.next ()) {Vector REC_Vector = New Vector (); // From Result Concentration Take Data Put Vector REC_Vector REC_VECTOR.ADDELEMENT (RS.GETSTRING (1)); REC_Vector.addelement (Rs.getstring (2)); REC_Vector.Addelement (Rs.getstring (3)); REC_Vector.AddeElement (Rs.Getdate (4)); REC_Vector .adDelement (NEW float); vect.addelement (REC_VECTOR); // Vector REC_Vector Add to Vector Vect} TM.FireTablestructureChanged (); // Update Table, Show Vector Vect

---- To implement the top of the drawing, the effect of the rear turn, there are two ways:

---- One, if the software environment supports JDBC2.0, you can use rsprevoius () and rs.next () to get records, then display individual field values ​​through the setText () method in class jTextField.

---- II, if JDBC2.0 is not supported, you can use the vector vector to remove the data in the JTABLE. Customize a pointer to record the location. When the pointer is added 1, take out the previous row data into the vector display; the pointer is reduced by 1, remove the next row data display. The display method is the same.

---- What you need to say is that the code is not given in the code, such as SQLEXCeption, you must give it in the actual application. In addition, in some systems, the Chinese characters in the text domain do not necessarily display properly and need to be implemented with other methods.

转载请注明原文地址:https://www.9cbs.com/read-31205.html

New Post(0)