DBCP 数据源获取连接
Main
package p1; import com.JdbcUtils; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class Main { public static void main(String[] args) throws Exception { // f1(); f2(); } private static void f1() throws SQLException { Connection conn = getDataSource().getConnection(); String sql = "UPDATE `user` set money=666 where id=?"; Object[] objs = new Object[]{"1"}; int res = JdbcUtils.executeUpdate(conn, sql, objs); System.out.println(res); } private static DataSource getDataSource() throws SQLException { BasicDataSource bs = new BasicDataSource(); bs.setDriverClassName("com.mysql.jdbc.Driver"); bs.setUrl("jdbc:mysql://localhost:3306/jdbc"); bs.setUsername("root"); bs.setPassword("xxx"); bs.setInitialSize(20); return bs; } private static void f2() throws Exception { Connection conn = getDataSource2().getConnection(); String sql = "UPDATE `user` set money=666 where id=?"; Object[] objs = new Object[]{"1"}; int res = JdbcUtils.executeUpdate(conn, sql, objs); System.out.println(res); } private static DataSource getDataSource2() throws Exception { Properties prop = new Properties(); prop.load(new Main().getClass().getClassLoader().getResourceAsStream("dbcpConfig.properties")); DataSource dataSource = BasicDataSourceFactory.createDataSource(prop); return dataSource; } }
dbcpConfig.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbc username=root password=xxx initialSize=20