【发布时间】:2014-12-02 20:03:38
【问题描述】:
我对通过 jdbc 关闭连接有点困惑。
package Login;
public class LoginFrame {
private JFrame loginFrame;
Connection conn = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginFrame window = new LoginFrame();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginFrame() {
initialize();
conn = DBConnect.connectDB();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setResizable(false);
loginFrame.setTitle("XXX");
loginFrame.setBounds(100, 100, 350, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Login", TitledBorder.LEADING, TitledBorder.TOP, null, SystemColor.inactiveCaptionText));
panel.setBounds(96, 140, 139, 99);
loginFrame.getContentPane().add(panel);
panel.setLayout(null);
loginField = new JTextField();
loginField.setBounds(47, 16, 86, 20);
panel.add(loginField);
loginField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(47, 37, 86, 20);
panel.add(passwordField);
JButton loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "select * from employees where login=? and password=?";
try{
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, loginField.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int countUsr = 0;
while(rs.next()){
countUsr++;
}
if(countUsr == 1){
loginFrame.dispose();
AdminFrame adminFrame = new AdminFrame();
adminFrame.setVisible(true);
}else if(countUsr > 1){
JOptionPane.showMessageDialog(null, "ERR");
}else{
JOptionPane.showMessageDialog(null, "ERR");
passwordField.setText("");
}
rs.close();
pst.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "ERR: "+e.getMessage());
}
}
});
loginButton.setBounds(25, 65, 89, 23);
panel.add(loginButton);
}
}
我不确定使用哪种方法更好地关闭连接:
@Override
protected void finalize() throws Throwable {
conn.close();
super.finalize();
}
或
finally {
conn.close();
}
在按钮 ActionListener 中的 try catch 块之后。
在某些示例中,人们说 finally 块更好,但是当我有很多方法(4 个示例动作侦听器)并且在每个方法中我都在 DB 上执行一些操作时,该怎么办。我应该在所有方法中打开和关闭连接还是只使用 finalize 方法?
【问题讨论】:
-
您应该在尽可能短的范围内打开和关闭连接。
-
如果您正在重用连接,那么您可以像第一个示例一样在完全完成后将其保持打开状态并关闭它。为每个函数创建新连接没有意义。
-
@brso05 如果连接超时,则无法重新使用连接。即使您使用来自数据库连接池的连接,您也应该调用
close方法。 -
我在另外 10 个 ActionListener 中重用了这个连接。 @Luiggi Mendoza 更好的方法是在每个 ActionListener 方法中使用 finally 块?这不是降低性能吗?
-
@LuiggiMendoza 您应该检查连接是否超时以及是否创建新连接。你实际上甚至不需要显式调用
close方法,它会自动关闭。