Java database application

Source: Internet
Author: User
Tags abstract definition class definition implement connect stmt sybase sybase database
Data | Database use Java to develop database application system, often need to display the query results in the user interface. As the jdk1.x Development Toolkit provided by Sun is not a visual integrated development environment (IDE), it is not easy to display the query results in DBGrid tables like Delphi and VB. Therefore, you can only write your own code to implement.
In practical application, we can solve this problem by using three kinds of vectors, JTable, Abstracttablemodel and so on. The following is a detailed introduction to the implementation method.

First, class vector, class JTable and Class Abstracttablemodel Brief introduction:

1, class vector:
Vector is the historical collection class of Java, subordinate to the Java.util package. It is packed with heterogeneous lists and arrays of miscellaneous, with the following two features:
* Vectors are heterogeneous and do not require the same type of each element, and can be mixed with multiple object types in vectors;
* Vectors are array hybrids because they can grow dynamically when adding elements.
Its heterogeneity coincides with the characteristics of different attribute types in the database records, and its dynamic nature coincides with the database query, the result set records the number of uncertain characteristics.
The vector is defined as follows:
public class Vector extends Abstractlist
Implements List, Cloneable, serializable{...}
The method of finding, adding and deleting vector members is realized. For example, add (object obj) makes it easy to add an object; get (int index) easily gets an object in the vector; Remove (object obj) makes it easy to delete an object in a vector.

2, Class JTable:
The JTable component is a relatively complex piece of swing components that is subordinate to the Javax.swing package and can display data as a two-dimensional table. The class jtable is defined as follows:
public class JTable extends JComponent
Implements Tablemodellistener, scrollable, Tablecolumnmodellistener,
Listselectionlistener, Celleditorlistener, accessible{...}
Class JTable has the following characteristics when displaying data:
* Customizable: Can customize the display of data and editing status;
* Heterogeneity: can display different types of data objects, even color, icon and other complex objects;
* Simplicity: A two-dimensional table can be easily established by default.
It can be customized to meet the requirements of different users and occasions, heterogeneity also coincides with the database access result set attribute types differ. Class JTable provides a very rich two-dimensional table operation methods, such as setting the editing status, display mode, select the ranks, and so on, not to repeat.
Before you use class JTable to display data, you must generate a custom model, unit drawing, or cell editor based on the situation. The class AbstractListModel is used to customize the user's own data model, which is described later. The Tablecellrenderer interface is used to customize the unit drawing, and the Tablecelleditor interface is used to customize the unit editor, which is used primarily for color object processing, not used in the example, and not overly descriptive.

3, Class Abstracttablemodel:
Class Abstracttablemodel is an abstract class that is not fully implemented and cannot be instantiated, and must be implemented in a program. It belongs to Javax.swing.table. The class definition is as follows:
Public abstract class Abstracttablemodel extends Object
Implements TableModel, serializable{...}
Class Abstracttablemodel provides the default implementation of most methods in the TableModel interface. The TableModel interface defines the underlying data structure of the jtable. The ability of a user to generate his or her own data model could have met the requirements by implementing all the methods in the TableModel interface, but the function of managing the audience table was common to all data models, So in Javax.swing.table, the class Abstracttablemodel is defined to handle this work. It manages both the audience table and facilitates the generation of tablemodelevents events and delegates 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);
At this point, we can build a simple two-dimensional table (5x5) to implement the following methods:
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 the database and its connection methods:
The example uses the Sybase database system, where the database resides in the database server. The path is: D:\WORKER, the database name is: WORKER.DBF. Has the following fields:
Field name
Type
WNO (Employee number)
VARCHAR
Wname (employee name)
VARCHAR
Sex (gender)
VARCHAR
Birthday (date of birth)
DATE
Wage (Salary)
FLOAT
To connect to this database, you use the class DriverManager in the java.sql package. This class is a utility class for managing JDBC drivers. It provides methods for obtaining connections through drivers, registering, revoking drivers, setting registrations and database access login timeouts, and so on. The specific connection method is as follows:
The first step: locating, loading and linking the Sybdriver class;
Driver= "Com.sybase.jdbc.SybDriver";
Sybdriver sybdriver= (sybdriver) class.forname (driver). newinstance ();
Step Two: Register Sybdriver class;
Drivermanager.registerdriver (Sybdriver);
Step three: Get the connection (sybconnection) object reference.
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, the database can be queried and changed through the statement interface.

Third, the realization method:
Limited to space, here only give the core code, package introduction, interface processing, variable definition and other parts are no longer introduced.
First step: Object declaration.
Abstracttablemodel tm;//declares a class Abstracttablemodel object
JTable jg_table;//declares a class JTable object
Vector vect;//declares a Vectorial object
JScrollPane jsp;//declares a scroll bar object
String title[]={"Employee Number", "Employee Name", "Sex", "date of birth", "salary"};
Two-dimensional table column name
Step two: Customize the table.
1, the implementation of abstract class Abstracttablemodel Object TM method:
Vect=new vector ();//instantiated vectors
Tm=new Abstracttablemodel () {
public int getColumnCount () {
return title.length;} Get the number of table columns
public int GetRowCount () {
return Vect.size ();} Get 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 value of a property in a cell
Public String getcolumnname (int column) {
return title[column];} Set table column name
public void setValueAt (Object value,int row,int column) {}
The data model is not editable, and the method is set to null
Public Class getcolumnclass (int c) {
Return getValueAt (0,c). GetClass ();
}//gets the object class that the column belongs to
public boolean iscelleditable (int row,int column) {
return false;} Set cell not editable, default implementation
};
2. Custom 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 Table Resize mode
Jg_table.setcellselectionenabled (false);//Set cell selection
Jg_table.setshowverticallines (TRUE);//Set whether to display a split line between cells
Jg_table.setshowhorizontallines (TRUE);
Jsp=new JScrollPane (jg_table)//Add a scroll bar to the table
Step three: Show query results.
1, connect the database: The second part has been given.
2, database query:
Statement stmt=connection.createstatement ();
ResultSet rs=stmt.executequery ("SELECT * from worker");
3, display the results of the query:
Vect.removeallelements ();//Initialize Vector object
Tm.firetablestructurechanged ()//Update table contents
while (Rs.next ()) {
Vector rec_vector=new vector ();
Take data from the result set into 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);//vector rec_vector join vector vect
}
Tm.firetablestructurechanged ()//Update table, display the contents of vector vect
The example diagram is as follows:

There are two ways to achieve the effect of turning on and off in an illustration:
First, if the software environment supports JDBC2.0, you can directly use Rs.prevoius () and Rs.next () to obtain records, and then through the class JTextField SetText () method, display the values of each field.
If you do not support JDBC2.0, you can use vector vectors to fetch the jtable data in rows. Customize a pointer to record the position. When the pointer plus 1 o'clock, remove the previous row of data into the vector display, the pointer minus 1 o'clock, take out the next line of data display. Display method Ibid.
It should be noted that the code does not give an exception to catch the part, such as SqlException, the actual application must be given. In addition, in some systems, the Chinese characters in the text field are not necessarily displayed correctly and need to be implemented by other means.



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.