扩展一个方法
1.直接改源码
2.继承,但必须知道接口的具体实现类
3.使用装饰者模式
面向接口编程
4.动态代理
通过装饰者方法重写链接的colse方法
JDBC的工具类
package util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtil {
static String driverClass = null;
static String url = null;
static String name = null;
static String password = null;
static {
try {
Properties properties = new Properties();
// InputStream is =new FileInputStream("jdbc.properties");
InputStream resourceAsStream = JDBCUtil.class.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(resourceAsStream);
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
name = properties.getProperty("name");
password = properties.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn(){
Connection conn = null;
try {
// DriverManager.registerDriver(new Driver());
conn = DriverManager.getConnection(url, name, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
private static void closeConn(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
conn = null;
}
}
}
private static void closeSt(Statement st){
if(st!=null){
try {
st.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
st = null;
}
}
}
private static void closeRs(ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
rs = null;
}
}
}
public static void release(Connection conn,Statement st,ResultSet rs){
closeRs(rs);
closeSt(st);
closeConn(conn);
}
public static void release(Connection conn,Statement st){
closeSt(st);
closeConn(conn);
}
}
数据库连接池
package util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.sql.DataSource;
/**
* 1.创建10个链接
* 2.对外获取链接的方法getConnection
* 3.归还链接addBack
* 4.扩容
* @author Administrator
*
*/
public class MyDataSource implements DataSource {
List <Connection> list = new ArrayList<Connection>();
public MyDataSource() {
for( int i = 0; i<10;i++){
Connection conn = JDBCUtil.getConn();
list.add(conn);
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
/**
* 链接池对外公布的获取链接的方法
*/
@Override
public Connection getConnection() throws SQLException {
if(list.size() == 0){
for( int i = 0; i<5;i++){
Connection conn = JDBCUtil.getConn();
list.add(conn);
}
}
Connection conn = list.remove(0);
Connection connection = new ConnectionWrap(conn, list);
return connection;
}
/**
* 使用之后归还链接
* @param conn
*/
public void addBack(Connection conn ){
list.add(conn);
}
@Override
public Connection getConnection(String arg0, String arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
装饰者类
package util;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
public class ConnectionWrap implements Connection {
Connection connection = null;
List<Connection> list ;
public ConnectionWrap(Connection connection,List<Connection> list) {
super();
this.connection = connection;
this.list = list;
}
@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void abort(Executor arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void close() throws SQLException {
list.add(connection);
}
@Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Array createArrayOf(String arg0, Object[] arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Statement createStatement(int arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Statement createStatement(int arg0, int arg1, int arg2) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Struct createStruct(String arg0, Object[] arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getClientInfo(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isValid(int arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public String nativeSQL(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String arg0, int arg1, int arg2) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0, int[] arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0, String[] arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0, int arg1, int arg2) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public PreparedStatement prepareStatement(String arg0, int arg1, int arg2, int arg3) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void releaseSavepoint(Savepoint arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void rollback(Savepoint arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setAutoCommit(boolean arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCatalog(String arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClientInfo(Properties arg0) throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public void setClientInfo(String arg0, String arg1) throws SQLClientInfoException {
// TODO Auto-generated method stub
}
@Override
public void setHoldability(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNetworkTimeout(Executor arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setReadOnly(boolean arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Savepoint setSavepoint(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setSchema(String arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTransactionIsolation(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException {
// TODO Auto-generated method stub
}
}
开源的数据库连接池
DBCP
通过设置的方法
//构建数据源对象
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Dreiver");
basicDataSource.setUrl("jdbc:mysql://localhost/test");
basicDataSource.setUsername("root");
basicDataSource.setPassword("root");
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
String sql = "select * from user where name = ? and password = ?";
try {
// 得到链接
conn = basicDataSource.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
JDBCUtil.release(conn, ps, rs);
}
通过配置的方法
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
String sql = "";
try {
InputStream is = new FileInputStream("src//dbcpconfig.properties");
Properties properties = new Properties();
properties.load(is);
DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
conn = dataSource.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
JDBCUtil.release(conn, ps, rs);
}
}
C3P0
通过设置
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
String sql = "select * from user where name = ? and password = ?";
try {
//构建数据源对象
ComboPooledDataSource basicDataSource = new ComboPooledDataSource();
basicDataSource.setDriverClass("com.mysql.jdbc.Dreiver");
basicDataSource.setJdbcUrl("jdbc:mysql://localhost/test");
basicDataSource.setUser("root");
basicDataSource.setPassword("root");
// 得到链接
conn = basicDataSource.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "password");
rs = ps.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
JDBCUtil.release(conn, ps, rs);
}
通过配置
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
String sql = "";
try {
// 会自动读取c3p0-config.xml
ComboPooledDataSource dataSource = new ComboPooledDataSource();
conn = dataSource.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
JDBCUtil.release(conn, ps, rs);
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/test</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
</c3p0>
使用c3p0的JDBC工具类
static ComboPooledDataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource();
}
public static Connection getConn() throws SQLException{
return dataSource.getConnection();
}
private static void closeConn(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
conn = null;
}
}
}
private static void closeSt(Statement st){
if(st!=null){
try {
st.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
st = null;
}
}
}
private static void closeRs(ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
rs = null;
}
}
}
public static void release(Connection conn,Statement st,ResultSet rs){
closeRs(rs);
closeSt(st);
closeConn(conn);
}
public static void release(Connection conn,Statement st){
closeSt(st);
closeConn(conn);
}
DBUTILS的使用(增删改查)
QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
// 增加
queryRunner.update("insert into user(usernam,password) values(?,?)","lisi","lisi");
// 修改
queryRunner.update("update user set username = ? where id = ?", "wangwu",3);
// 删除
queryRunner.update("delete from user where id =?", 10);
// 通过new接口匿名实现类查询
User user = queryRunner.query("select * from user where id = ?", new ResultSetHandler<User>(){
@Override
public User handle(ResultSet rs) throws SQLException {
User user = new User();
while(rs.next()){
user.setName(rs.getString("userName");
user.setPassord(rs.getString("password");
}
return user;
}},10);
// 单个查询
User user = queryRunner.query("select * from user where id = ?", new BeanHandler<User>(User.class),2);
// 多个查询
List<User> list = queryRunner.query("select * from user where id = ?", new BeanListHandler<User>(User.class),2);
for(User user : list){
user.toString();
}
数组
ArrayHandler
ArrayListHandler
对象
BeanHandler
BeanListHandler
map对象
MapListHandler