之前的DB层都是这样写的public class DBConnections {

protected Connection con = null;
protected Statement stmt = null;
protected ResultSet rs = null;
protected PreparedStatement pstmt=null; /**
 * 得到数据库连接
 * */
public void getOpen() {
try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=blogs","sa", "sa");
stmt = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
} /**
 * 关闭数据库
 * */
public void getClose() {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
 * 执行非查询操作语句
 * */
public int executeSQL(String sql) throws Exception {
return stmt.executeUpdate(sql);
} public ResultSet find(String sql) throws Exception {
rs = stmt.executeQuery(sql);
return rs;
}
}
现在同学用了数据池连接,写成了这样:
public static synchronized Connection getConnection()
{
String driverClassName=Env.getInstrance().getProperty("driver");
String url=Env.getInstrance().getProperty("url");
String password=Env.getInstrance().getProperty("password");
String user=Env.getInstrance().getProperty("user");
Connection con=null;



try
{
Class.forName(driverClassName);
con=DriverManager.getConnection(url,user,password);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return con;
}

public static void close(Connection con,Statement st,ResultSet rs)
{
try 
{
if(rs!=null)
{
rs.close();
}
if(st!=null)
{
st.close();
}
if(con!=null)
{
con.close();
}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}那么,现在问题来了,我在业务层之前是这样获取数据的:
pstmt=getConnection().prepareStatement(sql);
pstmt.setString(1, userName);
rs=pstmt.executeQuery();现在不知道业务层的数据怎么获取,求高手帮忙。

解决方案 »

  1.   

    数据池包含多个数据连接
    getConnection()方法就是得到一个数据连接
    你这样试正确的,
    pstmt=getConnection().prepareStatement(sql);
    pstmt.setString(1, userName);
    rs=pstmt.executeQuery();
    如果不在同一个类
    pstmt=类名.getConnection().prepareStatement(sql);
    pstmt.setString(1, userName);
    rs=pstmt.executeQuery();
    最好先判断getConnection().是否为NULL
    用完记得关闭
      

  2.   

    jsp-连接池
    “现在不知道业务层的数据怎么获取?”你写个通用DAO,再写实现DAO.然后在Biz调就行了没什么大差别。不过我一般都用JNDI来获取DataSource对象