
package cn.itcast.utils; |
import java.io.IOException; |
import java.io.InputStream; |
import java.sql.Connection; |
import java.sql.PreparedStatement; |
import java.sql.ResultSet; |
import java.sql.SQLException; |
import java.util.Properties; |
import javax.sql.DataSource; |
import org.apache.commons.dbcp.BasicDataSourceFactory; |
public class JdbcUtils { |
|
private static DataSource ds=null; |
static { |
try { |
InputStream intput=JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"); |
Properties pro=new Properties(); |
pro.load(intput); |
BasicDataSourceFactory factory=new BasicDataSourceFactory(); |
ds=factory.createDataSource(pro); |
} catch (Exception e) { |
throw new ExceptionInInitializerError(e); |
} |
} |
|
|
public static Connection getConnection() throws SQLException{ |
return ds.getConnection(); |
} |
|
public static void realease(Connection conn,PreparedStatement ps,ResultSet rs){ |
if(conn!=null){ |
try { |
conn.close(); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
conn=null; |
} |
|
if(ps!=null){ |
try { |
ps.close(); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
ps=null; |
} |
|
if(rs!=null){ |
try { |
rs.close(); |
} catch (SQLException e) { |
e.printStackTrace(); |
} |
rs=null; |
} |
} |
|
//用于对数据的增,删 ,改 |
public void update(String sql,Object params[]) throws SQLException{ |
Connection conn=null; |
PreparedStatement ps=null; |
ResultSet rs=null; |
try{ |
conn=getConnection(); |
ps=conn.prepareStatement(sql); |
for(int i=0;i<params.length;i++){ |
ps.setObject(i+1, params[i]); |
} |
ps.executeUpdate(); |
}finally{ |
realease(conn, ps, rs); |
} |
} |
|
//用于对数据的查找 |
public static Object query(String sql,Object params[],ResultSetHandler handler) throws SQLException{ |
Connection conn=null; |
PreparedStatement ps=null; |
ResultSet rs=null; |
try{ |
conn=getConnection(); |
ps=conn.prepareStatement(sql); |
for(int i=0;i<params.length;i++){ |
ps.setObject(i+1, params[i]); |
} |
rs=ps.executeQuery(); |
//由于不知道对结果集的处理,这个地方就暴露一个接口,让使用者去调用。 |
return handler.handel(rs); |
}finally{ |
realease(conn, ps, rs); |
} |
} |
} |




中级程序员
by: 中国人在美国 发表于:2013-07-31 05:09:30 顶(1) | 踩(0) 回复
代码挺规范的,可惜没银子
回复评论