Encapsulation | data | Database encapsulates database operations in order to hide the class in the java.sql package and remove the core database operation code from the encoding. In order to prevent the direct database operation easy to bring the resource not release problem. It also reduces the amount of coding for database operations.
But many netizens in the encapsulation, but like to return the result set (ResultSet object), then this encapsulation is meaningless.
1. It is also a direct operation of the core database class, with almost no changes before the package.
2. The result set always relies on the connection (Connection) object it uses. So when the connection object is closed within the method, the resultset you return is useless.
If you really want to get the result set of the query database, dump all the data in the result set object into the list object that is the map element.
Of course, this way, can not adapt to large amount of data query, but if you really encounter large data query, which package is not good, or direct database operations. :)))
The following is a simple database operation JavaBean Code
Dbwrapper.java
Import java.sql.*;
Import java.util.*;
public class Dbwrapper
{
Defining the connection pool object as a static variable will persist until the working directory is closed.
private static DataSource ds = NULL;
1. Connect by Connection Pool
This method is recommended if you are not a long database program
Related: Configuring connection pooling in the Tomcat management interface
public static Connection OpenConnection () throws Exception
{
Only need to initialize 1 times
if (ds = null)
{
Context Initcontext = new InitialContext ();
Context Envcontext = (context) initcontext.lookup ("java:/comp/env");
DataSource ds = (DataSource) envcontext.lookup ("Jdbc/mydatasource");
}
return Ds.getconnection ();
}
2. Use JDBC driver to get the connection
Related content: JSP database connection Encyclopedia
public static Connection OpenConnection (
String driver,
String URL,
String username,
String password)
Throws Exception
{
Class.forName (Driver). newinstance ();
Return drivermanager.getconnection (URL, username, password);
}
public static void CloseConnection (Connection conn) throws Exception
{
IF (conn!= null)
{
Conn.close ();
}
}
public static int executeupdate (String sql) throws Exception
{
int count = 0;
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.