日期:2014-05-19 浏览次数:20662 次
/** * @author Aray Chou * Email: Aray(dot)Chou(dot)CN(at)gmail(dot)com * Replace "(dot)" with "." and replace "(at)" with "@" */ package com.teenyee.frame.core.common.db; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Enumeration; import java.util.Properties; import javax.sql.DataSource; import com.mchange.v2.c3p0.DataSources; /** * 数据库工具 */ public final class DatabaseUtils { private final static String JDBC_URL; // private final static String JDBC_URL = // "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db1.95130951.com)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=db2.95130951.com)(PORT=1521))(LOAD_BALANCE=yes)(failover=yes)(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=db.yft)))"; private final static String JDBC_USER; private final static String JDBC_PASSWORD; static { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties"); Properties p = new Properties(); try { p.load(in); } catch (IOException e) { e.printStackTrace(); System.out.println(e); } JDBC_URL = (String) p.get("JDBC_URL"); JDBC_USER = (String) p.get("JDBC_USER"); JDBC_PASSWORD = (String) p.get("JDBC_PASSWORD"); }; // private final static String JDBC_PASSWORD = "zheshiframe"; private static DataSource dataSource; /** * @return 网络连接 * @throws SQLException */ public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } // test only public static void main(String[] argv) { try { System.out.println(getNextNo()); } catch (Exception e) { e.printStackTrace(); } finally { } } /** * 断开数据库连接池,20s后重新连接 */ public static void reconnect() { try { DataSources.destroy(dataSource); Thread.sleep(1000 * 20); } catch (Exception e) { e.printStackTrace(); } connect(); } public static void connect() { Driver driver; try { driver = (Driver) Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); java.sql.DriverManager.registerDriver(driver); } catch (Exception e) { e.printStackTrace(); } DataSource unpooled; try { unpooled = DataSources.unpooledDataSource(JDBC_URL, JDBC_USER, JDBC_PASSWORD); dataSource = DataSources.pooledDataSource(unpooled); } catch (SQLException e) { e.printStackTrace(); } } /** * 断开数据库连接池 */ public static void destroy() {