Database connection acquisition class based on Apache DBCP

Source: Internet
Author: User
Tags comments connection pooling getmessage tomcat stringbuffer

The Apache DBCP-based database connection acquisition class allows you to use Apache's database connection pool on a J2SE program or other application server other than Tomcat.


TODO: To increase the maximum number of connections and the minimum number of connections setting function

Configuration file:

Connectionfactory.properties

# 2004-12-30
# Database Connection Factory configuration file, class file see util. ConnectionFactory
# Debug flag, True when using a JDBC direct connection (using URL, driver, user, password four parameters)
# False when using the built-in database connection pool (using parameter Jdbc.jndi), the configuration file is in Db.properties
Debug=false
# JDBC's connection address URL
Jdbc.url=jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=yuelao
# JDBC Driver
Jdbc.driver=com.microsoft.jdbc.sqlserver.sqlserverdriver
# JDBC Connection User name
Jdbc.user=sa
# JDBC Connection Password
jdbc.password=
When the #debug is false, the database connection is obtained based on the connection pool name, which is useful when the program is running on the server

. Java files:

/*
* @ (#) Connectionfactory.java 1.2 2005-11-25
*
* Copyright 2005 Beansoft Studio. All rights reserved.
* Proprietary/confidential. Use are subject to license terms.
*/

Package beansoft.util;

Import Java.io.ByteArrayInputStream;
Import Java.io.FileOutputStream;
Import Java.io.FileWriter;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.SQLException;
Import java.util.Properties;

Import Javax.sql.DataSource;
Import Org.apache.commons.dbcp.BasicDataSource;

Import Beansoft.jsp.StringUtil;
Import Beansoft.sql.DatabaseUtil;

/**
* ConnectionFactory provide a factory class that produces all database
* connections from here, and it provid Es methods for shutdown and restart
* data sources as well as reading and saving configuration parameters from/to file.
*
* Database connection factory class, where all database connections are generated, provide methods for shutting down and restarting data sources, and the ability to read and save
* configuration parameters to a file.
*
* 2005-08-19
* Using Apache DBCP as database connection pool provider.
* Use Apache DBCP as the provider class for connection pooling.
*
* @link http://jakarta.apache.org/commons/dbcp/
*
* Dependency:
* Commons-collections.jar
* Commons-pool.jar
* Commons-dbcp.jar
* J2ee.jar (for the javax.sql classes)
*
* If your using this class with to MCAT ' s Web application, then all the above jars
* not need to being added because the Tomcat it self have included these CL The Libs.
* If you call this class in Tomcat's Web application, none of the above jars will be added as a separate
*, since Tomcat has already brought these class libraries by default.
*
* @author beansoft
* @version 1.2
* 2005-11-25
*/
public class ConnectionFactory {

/** Database Password */
private static String password;

/** Database Username */
private static String user;

/** JDBC URL */
private static String URL;

/**
* JDBC Driver class name
*/
private static String driver;

/**
* DEBUG flag, default value is True, returns a connection that directly fetched using
* JDBC API; If Falg is false, returns a connection returned by the connection pool,
* If u want depoly the application, please make this flag is false.
* Debug tag, the default value is True, returns the connection obtained directly using JDBC; If marked as false,
* This flag is set to False when the program is published from the connection pool in the return connection.
*/
private static Boolean DEBUG = true;

/** Connection Properties Value */
private static properties props = new properties ();

/** The data source object, added at 2005-08-19 */
private static DataSource DataSource = null;

Load Configuration from Resource/connectionfactory.properties
static {
Loadconfiguration ();
}

Private ConnectionFactory () {
}

/**
* Factory method:obtain a database connection.
* Factory method: Gets a database connection.
*
*
* @return Connection a Java.sql.Connection object
*/
public static Connection getconnection () {
try {
Connection conn = null;

Debug mode, obtain connection directly through JDBC API
if (DEBUG) {

Class.forName (driver);

conn = drivermanager.getconnection (URL, user, password);
} else {
Todo
Looking data source through JNDI tree
DataSource DataSource = (DataSource) getinitialcontext ()
. lookup (Jndi);
conn = Datasource.getconnection ();
conn = Setupdatasource (). getconnection ();
}

Return conn;
} catch (Exception ex) {
System.err.println ("error:unable to get a connection:" + ex);
Ex.printstacktrace ();
}

return null;
}

/**
* Load and parse configuration.
*/
public static void Loadconfiguration () {
try {
Props.load (New Bytearrayinputstream (Readconfigurationstring (). GetBytes ()));

Load DEBUG flag, default to True
debug = boolean.valueof (Props.getproperty ("Debug", "true"))
. Booleanvalue ();
Password = props.getproperty ("Jdbc.password", null);
user = Props.getproperty ("Jdbc.user", null);
url = props.getproperty ("Jdbc.url", null);
Driver = Props.getproperty ("Jdbc.driver");
} catch (Exception e) {
E.printstacktrace ();
}
}

/**
* Save the current configuration properties.
*/
public static void Saveconfiguration () {
Saveconfiguration (GetProperties ());
}


/**
* Read content string from the configuration file. Because Class.getresourceasstream (String)
* Sometimes cache the contents, so here used this method.
* Read the string in the configuration file.
* Because the class getResourceAsStream (String) method sometimes appears cached,
* This method has been used to the last resort.
* @return String, NULL if failed
*/
public static String readconfigurationstring () {
try {
Java.io.FileInputStream fin = new Java.io.FileInputStream (
Getconfigurationfilepath ());
Java.io.ByteArrayOutputStream bout = new
Java.io.ByteArrayOutputStream ();

int data;
while (data = Fin.read ())! =-1) {
Bout.write (data);
}
Bout.close ();
Fin.close ();

return bout.tostring ();
} catch (Exception ex) {
System.err.println ("Unable to load connectionfactory.properties:" +
Ex.getmessage ());
Ex.printstacktrace ();
}
return null;
}

/**
* Get The configuration file ' s real physical path.
*/
private static String Getconfigurationfilepath () {
Return Stringutil.getrealfilepath ("/connectionfactory.properties");
}

/**
* Save string content of a Java.util.Properties object.
* Save the string in the configuration file.
*
* @param props configuration string
* @return Operation result
*/
Protected static Boolean saveconfigurationstring (String props) {
if (props = = NULL | | props.length () <= 0) return false;
try {
FileWriter out = new FileWriter (Getconfigurationfilepath ());
Out.write (props);
Out.close ();

return true;
} catch (Exception ex) {
System.err.println ("Unable save configuration string to Connectionfactory.properties:"
+ ex);
Ex.printstacktrace ();
}

return false;
}

/**
* Returns The current database connection properties.
* @return Properties Object
*/
public static Properties GetProperties () {
return props;
}

/**
* Save Configuration Properties.
*
* @param props Properties
* @return Operation result
*/
public static Boolean saveconfiguration (Properties props) {
if (props = = NULL | | props.size () <= 0) return false;

try {
FileOutputStream out = new FileOutputStream (Getconfigurationfilepath ());
Props.store (Out, "");
Out.close ();

return true;
} catch (Exception ex) {
System.err.println ("Unable to save connectionfactory.properties:" + ex.getmessage ());
Ex.printstacktrace ();
}

return false;
}

/**
* Create a DataSource instance based on the Apache DBCP.
* Create DataSource based on Apache DBCP.
*
* @return a poolable DataSource
*/
public static DataSource Setupdatasource () {
if (DataSource = = null) {
Basicdatasource ds = new Basicdatasource ();
Ds.setdriverclassname (driver);
Ds.setusername (user);
Ds.setpassword (password);
Ds.seturl (URL);

DataSource = ds;
}

return dataSource;
}

/**
* Display Connection Status of current data source.
*
* Displays the status of the current data source.
*/
public static String Getdatasourcestats () {
Basicdatasource BDS = (basicdatasource) setupdatasource ();
StringBuffer info = new StringBuffer ();

Info.append ("Active connection numbers:" + bds.getnumactive ());
Info.append ("/n");
Info.append ("Idle connection numbers:" + bds.getnumidle ());

return info.tostring ();
}

/**
* Shut down the data source, if want use it again,
* Please call Setupdatasource ().
*/
public static void Shutdowndatasource () {
Basicdatasource BDS = (basicdatasource) setupdatasource ();
try {
Bds.close ();
} catch (SQLException e) {
TODO Auto Generated Try-catch
E.printstacktrace ();
}
}

/**
* Restart the data source.
* Restart the data source.
*/
public static void Restartdatasource () {
Shutdowndatasource ();
Setupdatasource ();
}

/** Test Method */
public static void Main (string[] args) {
Connection conn = Connectionfactory.getconnection ();

Databaseutil dbutil = new Databaseutil ();
Dbutil.setconnection (conn);

try {
Java.sql.ResultSet rs = conn.createstatement (). ExecuteQuery (
"Select MAX (ID) from items");
//
while (Rs.next ()) {
System.out.println (rs.getstring (1));
// }
//
Rs.close ();
//
} catch (Exception ex) {
Ex.printstacktrace ();
// }

System.out.println (Dbutil.getallcount ("Select MAX (ID) from items");

SYSTEM.OUT.PRINTLN (conn);

try {
Conn.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}

conn = Connectionfactory.getconnection ();

SYSTEM.OUT.PRINTLN (conn);

try {
Conn.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}

System.exit (0);
}

} posted on 2007-01-19 11:04 beansoft Read (2424) Comments (1)   Edit   Favorites Category: Database-- Comm Ents re: database connection based on Apache DBCP get Class (original) cart horse
Posted @ 2007-01-23 23:38 , has been used before, Apache a lot of things are very good,

Landlord, Potential stickers forum (HTTP/ content.uu1001.com) is a personal idea, if you are very focused on Java, and willing to make my friend, you can email me (lbw070105@gmail.com), I hope we can develop it together.    Reply    more comments    

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.