I'm little confused about closing connection by 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);
}
}
I'm not sure which metod is better to use to close connection:
@Override
protected void finalize() throws Throwable {
conn.close();
super.finalize();
}
or
finally {
conn.close();
}
after a try catch block in button ActionListener.
In some examples people say finally block is better but what when I have many methods(4example Action Listeners) and in every of them I do some operations on DB. Should I open and close connection in all methods or just use finalize method?