怎样处理这尴尬的代码
package com.shi.util;
import java.sql.*;
public class SQLHelp {
private static String name="scott";
private static String password="123";
private static String driver="oracle.jdbc.driver.OracleDriver";
private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
private static Connection ct;
private static PreparedStatement statement=null;
private static ResultSet resultset=null;
private String userPassword;
private String userName;
public String getUserName() {
return userName;
}
public String getUserPassword() {
return userPassword;
}
static
{
try {
Class.forName(driver);
ct=DriverManager.getConnection(url,name,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ResultSet query(String SQL,String premare[])
{
try {
statement=ct.prepareStatement(SQL);
if(premare!=null)
{
for(int i=0;i<premare.length;i++)
statement.setString(i+1, premare[i]);
}
resultset=statement.executeQuery();
} catch (
SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultset;
}
}
这里面的ct,statment,resultset都不能在本页关闭,怎样可以在调用的地方关掉这些流?
jdbc
------解决方案--------------------
ResultSet rs=null;
try{
rs=query("select * from...",params);
//TODO:do your job here
}finally{
Statement stmt=rs.getStatement();
Connection conn=stmt.getConnection();
//TODO:close them if you wish!
}
这是噩梦的开始,祝你好运!
------解决方案--------------------我建议楼主使用单体实例的那种方法,然后把其他的方法设置成私有的,然后同时建立一个关闭的方法,你在哪调用玩这个对象就在哪用这个对象去调用关闭的方法就可以了