首页 > 代码库 > Java-DBCP连接池
Java-DBCP连接池
创建项目:
导入jar包:
参见上图。
JDBCConn.java获取数据源类:
package com.gordon.jdbcconn; import java.io.InputStream; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; public class JDBCConn { private static String DRIVERNAME = null; private static String URL = null; private static String USER = null; private static String PASSWORD = null; private static BasicDataSource datasource = new BasicDataSource(); static { try { Properties props = new Properties(); InputStream in = JDBCConn.class.getClassLoader().getResourceAsStream("db.properties"); props.load(in); DRIVERNAME = props.getProperty("drivername"); URL = props.getProperty("url"); USER = props.getProperty("user"); PASSWORD = props.getProperty("password"); } catch (Exception e) { throw new RuntimeException(e); } } public static DataSource getDatasource() throws Exception { /* driverClassName 数据库驱动名称 url 数据库的地址 username 用户名 password 密码 maxActive 最大连接数量 minIdle 最小空闲连接 maxIdle 最大空闲连接 initialSize 初始化连接 */ datasource.setDriverClassName(DRIVERNAME); datasource.setUrl(URL); datasource.setUsername(USER); datasource.setPassword(PASSWORD); return datasource; } }
DBCPTest.java测试类:
package com.gordon.dbcp; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ArrayListHandler; import com.gordon.jdbcconn.JDBCConn; public class DBCPTest { public static void main(String[] args) { try { selectFunction(); insertFunction(); selectFunction(); } catch (Exception e) { System.out.println(e.getMessage()); } } public static void insertFunction() throws Exception { QueryRunner qr = new QueryRunner(JDBCConn.getDatasource()); String sql = "INSERT INTO user (name) VALUES (?)"; Object[] params = {"testname"}; int res = qr.update(sql, params); if(res > 0) { System.out.println("insert success."); } else { System.out.println("insert faild."); } } public static void selectFunction() throws Exception { QueryRunner qr = new QueryRunner(JDBCConn.getDatasource()); String sql = "SELECT * FROM user"; Object[] params = {}; List<Object[]> objList = qr.query(sql, new ArrayListHandler(), params); for (Object[] objs : objList) { for (Object obj : objs) { System.out.print(obj + " "); } System.out.println(); } } }
Java-DBCP连接池
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。