package org.wdj;import java.sql.*;public class Success { /**
 * @param args
 */

private Connection con=null; 
private final String DRIVER="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private final String URL="jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=test";
private final String name="sa";
private final String pass="sa";
private PreparedStatement pstm=null;
private ResultSet rs=null;                 
private String sql="select * from biao";
public Success(){
try{
Class.forName(DRIVER);
con=DriverManager.getConnection(URL,name,pass);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成方法存根
Success s=new Success();
s.disp();
}
public void disp(){
try{
rs=con.prepareStatement(sql).executeQuery();
while(rs.next()){
System.out.print(rs.getString(2));
}
pstm.close();
rs.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}


}}
 这个是代码,我怎么才能关闭pstm呢,在哪里写关闭合适呢?

解决方案 »

  1.   

    pstm.close();
    rs.close();
    con.close();写finally里
      

  2.   

    //添加纪录
        public boolean add() {
            //在此实现插入记录功能
            try{
                con = objConnManager.getCon();
                strSql = "insert into Article values(?,?,?,?,?,?,null)";
                pstmt = con.prepareStatement(strSql);
                pstmt.setInt(1,this.getAuid());
                pstmt.setString(2,this.getAtitle());
                pstmt.setString(3,this.getAcontent());
                pstmt.setInt(4,this.getAtype());
                pstmt.setInt(5,this.getAstate());
                pstmt.setString(6,this.getAtime());
                //pstmt.setString(7,this.get);
                pstmt.executeUpdate();
                con.close();
                return true;
            }catch (SQLException sqlex) {
                //JOptionPane.showMessageDialog(new JFrame(), sqlex);
                System.out.println(sqlex);
            } catch (Exception ex) {
                //JOptionPane.showMessageDialog(new JFrame(), ex);
                System.out.println(ex);
            }finally{
                try{
                    if(con!=null)
                        con.close();
                }catch(SQLException sqlex){System.out.println(sqlex);}
            }
            return false;
        }
      

  3.   

    to woaijava007 ():   
    很简单
    因为 private PreparedStatement pstm=null;
    你自始至终都没有用到pstm,也没有让他指向一个PreparedStatement对象
    所以  他一直是null