DBManagement
DBManagement/** * * @main This class manager DB connect for a application. * * @author yb * @version 1.0 * @date 2010.4.1 */ import java.sql.Connection; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; public class DBManagement { private static ComboPooledDataSource cpds = null; static { try { DBManagement.getDataSource(); } catch (SQLException e) { e.printStackTrace(); } } public static void getDataSource() throws SQLException { cpds = new ComboPooledDataSource(); } public static void destroyDataSource() throws SQLException { // 判断连接池是否存在 if (cpds != null) { // 调用C3P0接口,关闭数据库连接池 DataSources.destroy(cpds); } } public static Connection getConnection() throws SQLException { // 判断连接是否已经创建 if (cpds == null) { // 如果没有创建,则新创建一个 getDataSource(); } // 从连接池中取出一个数据库连接 return cpds.getConnection(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
DBblogic
DBblogicimport java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBblogic { /** * * @param table * @param con * 完整的条件 */ public void selectTable(String table, String con) { try { Connection conc = DBManagement.getConnection(); String sql = ""; if (con == null) { sql = "SELECT * FROM " + table; } else { sql = "SELECT * FROM " + table + " where " + con; } PreparedStatement pstmt = conc.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1) + rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { DBManagement.destroyDataSource(); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库重载释放错误 err02"); } } } /** * @param args */ public static void main(String[] args) { DBblogic dd = new DBblogic(); dd.selectTable("user", null); } }