关于Java关闭Connection资源的问题 求大家帮帮忙
try {
String sname=tname.getText();
String sphone=tphone.getText();
String sqq=tqq.getText();
String srelation=(String) crelation.getSelectedItem();
String semall=temall.getText();
String saddress=taddress.getText();
String sremark=tremark.getText();
// Class.forName("com.mysql.jdbc.Driver");
// Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "968543");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1434;DatabaseName=addressbook;user=sa;password=968543");
Statement st = conn.createStatement();
String test= "insert jinformation values('"+username+"',"+"'"+1+"',"+"'"+sname+"',"
+"'"+sphone+"',"+"'"+sqq+"',"+"'"+srelation+"',"+"'"+semall+"',"+"'"+saddress+"',"
+"'"+sremark+"')";
System.out.print(test);
st.executeUpdate(test);
st.close();
conn.close();
} catch (Exception e1) {
JOptionPane.showMessageDialog(jf," 请输入正确的值", "警告",JOptionPane.INFORMATION_MESSAGE,new ImageIcon("image\\(37).gif"));
}
当我发生异常时conn的资源没被关闭 再运行的话就会出异常
这种情况我改如何去关闭呢?
------解决方案--------------------
Connection conn = null;
try {
String sname=tname.getText();
String sphone=tphone.getText();
String sqq=tqq.getText();
String srelation=(String) crelation.getSelectedItem();
String semall=temall.getText();
String saddress=taddress.getText();
String sremark=tremark.getText();
// Class.forName("com.mysql.jdbc.Driver");
// Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "968543");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1434;DatabaseName=addressbook;user=sa;password=968543");
Statement st = conn.createStatement();
String test= "insert jinformation values('"+username+"',"+"'"+1+"',"+"'"+sname+"',"
+"'"+sphone+"',"+"'"+sqq+"',"+"'"+srelation+"',"+"'"+semall+"',"+"'"+saddress+"',"
+"'"+sremark+"')";
System.out.print(test);
st.executeUpdate(test);
st.close();
} catch (Exception e1) {
JOptionPane.showMessageDialog(jf," 请输入正确的值", "警告",JOptionPane.INFORMATION_MESSAGE,new ImageIcon("image\\(37).gif"));
}finally{
conn.close();
}
------解决方案--------------------
Connection conn = ... ;
关闭一般都是
try{
}catch(...){
}finally{
if (conn != null && !conn.isClose()){
conn.close() ;
}
}