C3P0:数据库连接池技术
* 步骤:
1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
* 不要忘记导入数据库驱动jar包
2. 定义配置文件:
* 名称: c3p0.properties 或者 c3p0-config.xml
* 路径:直接将文件放在src目录下即可。
3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
4. 获取连接: getConnection
* 代码:
//1.创建数据库连接池对象
DataSource ds = new ComboPooledDataSource();
//2. 获取连接对象
Connection conn = ds.getConnection();
JDBC工具类
package utils; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; /** * JDBC工具类 */ public class JDBCUtils { private static String driver; private static String url; private static String user; private static String password; /** * 文件的读取,只需要一次即可拿到这些值。使用静态代码块 */ static { //读取资源文件,获取值 try { //1、创建Properties集合类 Properties pro =new Properties(); //获取src路径下文件的方式-->ClassLoader类加载器 ClassLoader classLoader=JDBCUtils.class.getClassLoader(); URL resurl = classLoader.getResource("jdbc.properties"); String path=resurl.getPath(); //2、加载文件 pro.load(new FileReader(path)); //3、获取数据,赋值 driver=pro.getProperty("driver"); url=pro.getProperty("url"); user=pro.getProperty("user"); password=pro.getProperty("password"); //4、注册驱动 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取连接 * @return 连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } /** * 释放资源 * @param stmt * @param conn */ public static void close(Statement stmt,Connection conn){ if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs,Statement stmt, Connection conn){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }