JDBC basic application instance

Source: Internet
Author: User
After learning about basic JDBC knowledge, we will first write a database operation class (bean ).
Based on this class, we will continue to provide optimization solutions with the in-depth introduction.
To separate a database operation into a bean, consider the following aspects:
1. For applications at different levels, there should be different methods to get links.
As the application layers change, we should separate them into a specialized class, instead of at any application level.
The common processing methods are encapsulated in a (class) bean.
2. Since it can be used as both a JavaBean and a common class call
And the flexibility of common classes.
3. A specific database operation should not be encapsulated into a common (class) bean, but should be its extension class.

The above points fully consider the Java image object concept. After in-depth abstraction
We will follow this idea to design:
1. Define a bean for Link. If you want to use it in different applications in the future, for example
Datasource to get the link, or get the link from the normal connection pool, and directly get the link from drivermanager.
Link. You only need to modify the implementation method of the link in this class.
Package com. imnamg. axman. beans;
Import java. SQL .*;
Import ..................
Public class connectionfactory {
Protected connection conn;
Connectionfactory () throws sqlexception
{// Generate a link in the constructor
// Get the link from datasource or drivermanager directly.
// Initialize the environment first, and then obtain the link. This example is used as the initial application.
// Get the link in drivermanager. Because it is an encapsulation class, you need to throw an exception.
// Call it Program Instead of using the try {} catch () {} block for processing.
// Because it is necessary to inherit the class of the Business Method and cannot be accessed for all calls
// Conn declared as protected
Conn = drivermanager. getconnection (URL, user, passwd );
}

/**
In multi-threaded programming, it is often possible to get the same connection in multiple thread bodies.
But if the link is closed in one thread, the other gets the same
The referenced thread cannot be operated, so we should add a new connection.
Some people ask why this is not directly called since this helper method is available.
To generate links in the constructor? Because this can increase efficiency, if
If a link cannot be generated during construction, the object cannot be generated.
After the object is generated, test whether the link can be generated.
*/
Public void makeconnection (){
// Code Constructor
// Copy the code to this directory.
Conn = drivermanager. getconnection (URL, user, passwd );
}
}

this class is encapsulated here. Of course you can add business methods here, but if you want to modify the Implementation of The Link,
the entire class must be re-compiled, because the business method has nothing to do with the application layer, once the code is generated, it is not easy to change, so it is encapsulated independently.
here are our business methods:

package COM. imnamg. axman. beans;
Import Java. SQL. *;
Import ..................
public class dboperater extends connectionfactory {
// Private statement stmt;
// Private resultset RS;
// Why Do I Need To comment out the member variables stmt and RS? As mentioned in the basic section, if it is declared as a member variable,
// when the Conn is disabled, the RS and stmt can be disabled first, but the display is off.
// close only indicates that your programming style is good, however, to generate multiple stmt or non-type
// stmt cannot be declared as a member method; otherwise, the same object is referenced, therefore, we need to generate
// stmt object in the business method. it can not only process multiple result sets at the same time, but also improve performance and flexibility.

Public resultset executequery (string SQL) throws sqlexception {
If (conn = NULL | conn. isclosed ())
Makeconnection ();
Statement stmt = con. createstatement (
Resultset. type_scroll_insensitive,
Resultset. concur_read_only );
// For general query operations, we only need to generate a flow result set.
// For records to be updated during query, we use another business method,
// This saves the space for rollback during normal queries.
Resultset rs = stmt.exe cutequery (SQL );
Return Rs;
}

Public resultset executeupdatabledquery (string SQL) throws sqlexception {
If (con = NULL | con. isclosed ())
Makeconnection ();
Statement stmt = con. createstatement (
Resultset. type_scroll_insensitive,
Resultset. concur_updatabled );
// The updatable result requires a larger space for rollback. Do not call this method during normal queries.
Resultset rs = stmt.exe cutequery (SQL );
Return Rs;
}

/**
For the same reason, we do not need to roll back any space during the update operation.
A basic type of stmt is implemented as follows:
*/

Public int executeupdate (string SQL) throws sqlexception {
If (con = NULL | con. isclosed ())
Makeconnection ();
Statement stmt = con. createstatement ();
// This stmt saves more memory when performing the update operation. Always remember to save it when it can.
// Each byte of memory, although the hardware device may have a large physical memory, the memory is used
// Users rather than programmers (!!!!!!!!!!!!!!!!!!)
Int S = stmt.exe cuteupdate (SQL );
Return S;
}

// The above provides common functions, and two other common functions are also \ "common \". We will combine them in this encapsulation class.
// Implementation:
Public preparedstatement getpreparedstmt (string SQL) throws sqlexception {
If (con = NULL | con. isclosed ())
Makeconnection ();
Preparedstatement PS = con. preparestatement (SQL );
Return pS;
}
Public callablestatement getcallablestmt (string SQL) throws sqlexception {
If (con = NULL | con. isclosed ())
Makeconnection ();
Preparedstatement PS = con. preparecall (SQL );
Return pS;
}

// Remember: preparedstatement should be returned from the link for precompiled statements and stored procedure calls for encapsulation classes
// And callablestatement are used by the caller rather than returning their processing results. That is, the encapsulation class is only
// Install their link process. At last, declare again, there must be a close () method for the caller to call, and
// Whether the caller wants to call this method:

Public void close () throws sqlexception {
If (Conn! = NULL &&! Conn. isclosed ())
Conn. Close ();
}
// It is best to put this method in connectionfactory, so that you can call it directly to test the connection only.
Disable using subclass
}

OK. We have implemented the encapsulation of Common Database Operations. Note that these business methods are useless when throwing exceptions to callers.
Try... catch. If you have processed it here, the caller will not be able to debug it. For special operations on a specific database, do not seal
It can be inherited from this class or directly from the connectionfactory class. Of course, it is best to inherit from this business class,
In this way, not only special methods can be called, but also common business methods can be called. For example, when applying Oracle, I need to directly import XML files
To store data and directly read the data as an XML file, these two methods are only used for Oracle, so:

Package com. inmsg. axman. beans;

Import java. SQL .*;
Import oracle. xml. SQL. query. oraclexmlquery;
Import oracle. xml. SQL. DML. oraclexmlsave;

Public class extends ledboperater extends dboperater {
Public oraclexmlquery getoxquery (string SQL, string table) throws exception
{
Oraclexmlquery qry = new oraclexmlquery (con, SQL );
Qry. setrowsettag (table );
Qry. setrowtag (\ "record \");
Return qry;
}
Public int insertxml (string path, string table) throws exception
{
Oraclexmlsave sav = new oraclexmlsave (con, table );
URL url = Sav. createurl (PATH );
Sav. setrowtag (\ "record \");
Int x = Sav. insertxml (URL );
Sav. Close ();
Return X;
}
}

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.