标签:stat apach file factor inpu 1.5 dbcp nal ring
1 //DBCP代码演示: 2 public class DbcpDemo { 3 public static void main(String[] args) { 4 //通过dbcp连接池获取链接 5 BasicDataSource bDataSource = new BasicDataSource(); 6 //设置参数 7 bDataSource.setDriverClassName("com.mysql.jdbc.Driver"); 8 bDataSource.setUsername("root"); 9 bDataSource.setPassword("root"); 10 bDataSource.setUrl("jdbc:mysql://localhost:3306/test"); 11 Connection conn=null; 12 try { 13 //获取链接池中的链接 14 conn = bDataSource.getConnection(); 15 System.out.println(conn); 16 } catch (SQLException e) { 17 e.printStackTrace(); 18 }finally { 19 if (conn!=null) { 20 try { 21 //虽然调用close方法,但是连接池通过装饰者模式,修改了close方法 22 //实际的功能是释放链接回连接池中 23 conn.close(); 24 } catch (SQLException e) { 25 e.printStackTrace(); 26 } 27 } 28 } 29 } 30 } 31 //输出结果: 32 jdbc:mysql://localhost:3306/test, UserName=root@localhost, MySQL Connector Java
1 //DBCP通过配置文件代码演示: 2 //配置文件: 3 driverClassName=com.mysql.jdbc.Driver 4 username=root 5 password=root 6 url=jdbc:mysql://localhost:3306/tes
1 //演示代码: 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.sql.Connection; 6 import java.sql.SQLException; 7 import java.util.Properties; 8 9 import javax.sql.DataSource; 10 11 import org.apache.commons.dbcp.BasicDataSourceFactory; 12 /** 13 * 通过配置文件使用连接池 14 * @author zxy 15 * 16 */ 17 public class Demo { 18 public static void main(String[] args) { 19 //创建properties对象 20 Properties prop = new Properties(); 21 Connection conn=null; 22 try { 23 //加载配置文件,传入输入流 24 prop.load(new FileInputStream("src/dbcp.properties")); 25 //获取链接 26 DataSource bs = BasicDataSourceFactory.createDataSource(prop); 27 conn = bs.getConnection(); 28 //测试输出 29 System.out.println(conn); 30 } catch (FileNotFoundException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 }finally { 37 //关闭链接 38 if (conn!=null) { 39 try { 40 conn.close(); 41 } catch (SQLException e) { 42 e.printStackTrace(); 43 } 44 } 45 } 46 } 47 }
标签:stat apach file factor inpu 1.5 dbcp nal ring
原文地址:http://www.cnblogs.com/anzhi/p/7465178.html