给我发一个我上课学习用到的JDBC工厂
- package com.linguofeng.factory;
- import java.sql.Connection;
- import java.sql.SQLException;
- import org.apache.commons.dbcp.BasicDataSource;
- public class ConnectionFactory {
- private static BasicDataSource bds = new BasicDataSource();
- static {
- bds.setDriverClassName("com.mysql.jdbc.Driver");
- bds.setUrl("jdbc:mysql://127.0.0.1/mysql");
- bds.setUsername("root");
- bds.setPassword("root");
- bds.setMaxActive(2000);
- bds.setMaxIdle(20);
- bds.setMaxWait(5000);
- }
- public ConnectionFactory() {
- }
- public static java.sql.Connection getConnection() {
- java.sql.Connection con = null;
- try {
- con = bds.getConnection();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return con;
- }
- public static void close(java.sql.Connection con, java.sql.Statement stm,
- java.sql.ResultSet rs) {
- try {
- if (rs != null) {
- rs.close();
- rs = null;
- }
- if (stm != null) {
- stm.close();
- stm = null;
- }
- if (con != null) {
- con.close();
- con = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- // 使用方法
- Connection con = ConnectionFactory.getConnection();
- System.out.println(con);
- }
- }
复制代码 |