DBhelper:import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;/**
 * @author Kroda
 *
 */
public class DBHelper {
private Connection conn;
public Connection getConn()
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn=DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=;databaseName=master");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
conn=null;

return conn; }

public boolean ExecuSQL(String sql,PreparedStatement pstmt)
{

try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
int i=pstmt.executeUpdate();
if(i<1)return false;

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}finally
{
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return true;
}
}
其中一个调用类:
UserDAO:mport java.sql.PreparedStatement;
import VO.UserVo;
public class UserDAO {
private PreparedStatement pstmt;
public boolean InsertUser(UserVo user)
{
String strSQL="insert into test values(?,?,?)";
pstmt =new PreparedStatement();//会出错,其实我真的很想这么写,不好意思我从C#转过来的
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getUsername());
pstmt.setString(3, user.getUsername());
new DBHelper().ExecuSQL(strSQL, pstmt);

}

}我的意图就是Connection统一在DBHelper中打开和关闭,调用DBhelper的类[这里是UserDAO]只需要写个SQL语句,然后配一下传的参数递过去就行了。
不知道怎么干。。JAVA里能实现我要的这样么

解决方案 »

  1.   

    这样的写的好处 我就是想不让调用者(1)每次手动打开和关闭Connection,而是直接在DBhelper里ExecuSQL这个方法,让他自动打开关闭Connection
    1:假如有N个插入修改的方法岂不是每次都需要打开和关闭
      

  2.   

    做成回调形式的。比如:public interface ExecuSQLCallback{
    public void setParameter(PreparedStatement pstmt);
    }
    public class UserDAO {
        private PreparedStatement pstmt;
        public boolean InsertUser(UserVo user)
        {
            String strSQL="insert into test values(?,?,?)";        new DBHelper().ExecuSQL(strSQL, new ExecuSQLCallback(){
                public void setParameter(PreparedStatement pstmt){
                            pstmt.setString(1, user.getUsername());
                            pstmt.setString(2, user.getUsername());
                            pstmt.setString(3, user.getUsername());
                }
            });
            
        }
        
      

  3.   

    你这么写 new DBHelper().ExecuSQL(strSQL, new ExecuSQLCallback(){
    ExecuSQL提示错误...照你这种写法DBhelper用改吗错误是:
    The method ExecuSQL(PreparedStatement) in the type DBHelper is not applicable for the 
     arguments (new ExecuSQLCallback(){})
    CSDN怎么回事。。回复都不行了