DButil
纲要:
Properties prop = new Properties();
BasicDataSource ds = new BasicDataSorce();
Connection conn = ds.getConnection();
==================
package util;
import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
/** * 该类用来管理连接 * 数据库连接信息,保存在属性文件中 * 使用连接池获取连接 */ public class DBUtil { private static BasicDataSource ds; static{ try { //加载属性文件数据 Properties prop = new Properties(); prop.load (DBUtil.class.getClassLoader(). getResourceAsStream ("db.properties")); String driverclass = prop.getProperty("jdbc.driverclass"); String url = prop.getProperty("jdbc.url"); String user = prop.getProperty("jdbc.user"); String password = prop.getProperty("jdbc.password"); String strMaxActive = prop.getProperty("dbcp.maxActive"); String strInitSize = prop.getProperty("dbcp.initSize"); //实例化,并初始化连接池 ds = new BasicDataSource(); ds.setDriverClassName(driverclass); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setMaxActive (Integer.parseInt(strMaxActive)); ds.setInitialSize (Integer.parseInt(strInitSize)); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException ("读取属性文件错误",e); } } //2、创建连接 public static Connection getConnection() throws SQLException{ return ds.getConnection(); } //3、归还连接 public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException ("归还连接错误!",e); } } } //测试 public static void main(String[] args) throws SQLException { Connection conn = getConnection(); System.out.println (conn.getClass().getName()); close(conn); } }