JDBC primary application example (1)
After understanding the JDBC basic knowledge, let's write a class of database operations (Bean) after we will provide an optimized program based on the in-depth steps.
To operate a database operation to a class (bean), at least the following aspects:
1. For different levels of applications, there should be different ways to link. The processing method common in the hierarchy is encapsulated into a (class) bean.
2. Since it takes into consideration of both JavaBean uses for a common class, take into account the JavaBean's specification and the flexibility of ordinary classes.
3. For specific database operations should not be encapsulated into a common (class) bean, but it should be its extended class.
The above is to fully consider the idea of Java's iconic object. After in-depth abstraction, we will design it according to this idea:
One: Define a bean for connecting, if you want to get a connection from DataSource from DataSource in J2EE, or from the ordinary connecting pool, just need to connect directly from the DRIVERMANAGER Modify the implementation method of obtaining the connection in this class.
Package com.Imnamg.axman.beans;
Import java.sql. *;
Import ................
Public class connectFactory {
Protected connection conn;
ConnectionFactory () THROWS SQLEXCEPTION
{// structure method generating connection
// Whether it is from DataSource or a link from DRIVERMANAGER.
// First initialize the environment, then get a link, this example is an initial application, from
The link is achieved in // driverManager, because it is a package, so it is necessary to throw an exception
// Process the program to call it without using the try {} catch () {} block.
// Because it is inherited to the class of the business method, it cannot be accessed to call, so
// conn declaration is protected
Conn = drivermanager.getConnection (URL, USER, PASSWD);
}
/ **
In multi-threaded programming, many times there is a possibility to connect in multiple lines.
The reference is referenced, but if the connection is closed in a thread, the other is the same
The referenced thread will not operate, so we should add a re-establishment link.
Auxiliary method, someone asks why since this auxiliary method does not call this
Support to generate links in the construction method? Because this can increase efficiency, if
If you can't generate a link during construction, you can't generate this object, no need to
After the object is generated, the test can not generate a connection.
* /
Public void makeconnection () {
// The code is the same as a construction method, no matter if it is achieved, the constructor will be
// The code is copied here.
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 recompile because the business method is not related to the application level, the code is not easily changed, so the independent package. We realize business methods:
Package com.Imnamg.axman.beans;
Import java.sql. *;
Import ................
Public Class Dboperater Extends ConnectionFactory {
// private statement stmt;
// Private results RS;
/ / Why is the member variable STMT and RS, the base part has been said, if the declaration is a member variable,
// You can display the RS and STMT before turning off the CONN, there is no benefit, and the display is displayed.
// Closed just explain that you have a good programming, but consider, we have to generate multiple STMT or not type
// STMT can not be declared as a member method, otherwise it will reference the same object, so we have to be born in business methods.
// is a STMT object. Not only can you handle multiple result sets simultaneously, but also improve performance and flexibility. Public Result ExecuteQuery (String SQL) throwxception {
IF (conn == null || conn.isclosed ())
Makeconnection ();
Statement Stmt = Con. CreateStatement
ResultSet.Type_Scroll_InSensitive,
ResultSet.concur_read_only);
/ / For a general query operation, we only need to generate a flowable result set.
// For updating records in the query, we use another business method to handle, so
// This can save rollback space in normal query.
ResultSet RS = Stmt.executeQuery (SQL);
Return RS;
}
Public ResultSet ExecuteUpdatabledQuery (String SQL) THROWS SQLEXCEPTION {
IF (con == null || con?closed ())
Makeconnection ();
Statement Stmt = Con. CreateStatement
ResultSet.Type_Scroll_InSensitive,
ResultSet.concur_updatated;
/ / The updated result is a bigger rollback space, do not call this method when normal query
ResultSet RS = Stmt.executeQuery (SQL);
Return RS;
}
/ **
Based on the same reason, the implementation of the update operation is not to roll room at all, so established
A basic type of STMT is achieved
* /
Public int executeUpdate (String SQL) throws Sqlexception {
IF (con == null || con?closed ())
Makeconnection ();
Statement Stmt = con.createstatement ();
// This STMT saves memory when performing an update operation, always remember, save time to save
/ / Each byte memory, although the hardware device may have a lot of physical memory, but the memory is used
// Household rather than for programmers (!!!!!!!!!!!!!!!!!)
INT S = Stmt.executeUpdate (SQL);
Return S;
}
// The above has achieved common functions, and two universal features are also / "common /", let's take this package class
/ / Realization:
Public preparedStatement getPreparedStMt (String SQL) throws sqlexception {
IF (con == null || con?closed ())
Makeconnection ();
PreparedStatement PS = Con.PrepareStatement (SQL);
Return PS;
}
Public callablestatement getcallablestmt (String SQL) throws sqlexception {
IF (con == null || con?closed ())
Makeconnection ();
PreparedStatement PS = Con.PrepareCall (SQL);
Return PS;
}
// Remember: For the package class, the predetermined statement and stored procedure call should return PREPAREDSTATEMENT from the connection.
// and CallableStatement For the caller process rather than return their processing results. That is to say, the package is only sealed.
// Installed their connection process. Finally, declare it again, must have a close () method for call, and the note // complainant no matter if you want to call this method:
Public void close () throws sqlexception {
IF (conn! = null &&! conn.isclosed ())
CONN.CLOSE ();
}
// This method is best placed in ConnectionFactory, which can be directly called only test link. Not to use
Call the subclass to close
}
OK, we have implemented the packaging of the database commonly used operation, pay attention to these business methods to handle exceptions to the caller without using try ... catch, if you handle the caller, you can't debug. For Special operation of a specific database, do not encapsulate this class, you can inherit from this class, or directly from the ConnectionFactory class, of course, it is best to inherit from this business class, which can also call the commonality can also be called. Business method, Xing an example, I want to save the XML file directly to the number of data and send the data to an XML file directly, then these two methods are only used to Oracle, so:
Package com.inmsg.axman.beans;
Import java.sql. *;
Import oracle.xml.sql.query.OraclexmlQuery;
Import oracle.xml.sql.dml.Oraclexmlsave;
Public class oracledboperater extends dboperater {
Public OracleXmlQuery GetoxQuery (String SQL, String Table) THROWS EXCEPTION
{
OracleXmlquery Qry = New OracleXMLQuery (con, sql);
QRY.SetRowSettag (TABLE);
QRY.SETROWTAG (/ "rord /");
Return Qry;
}
Public int insertXML (String Path, String Table) Throws Exception
{
OracleXmlsave SAV = New OracleXmlsave (Con, Table);
URL URL = sav.createurl (path);
Sav.setrowtag (/ "rord /");
INT x = sav.insertxml (URL);
Sav.close ();
Return X;
}
}
Now, there are several "things /" in your hand, what do you think is inconvenient?
Although the site is a primary application, the design idea is already a java master, is it a bit self-blow?
Ok, take a break.