T
T
TheRevan2018-01-18 09:48:43
Java
TheRevan, 2018-01-18 09:48:43

When and how to close the connection to the java database?

There is this class:

public class MySQLConntection {
    private static final String HOST = "HOST";
    private static final String USERNAME = "BD_name";
    private static final String PASSWORD = "bd_pass";

    private Connection connection;

    public MySQLConntection() {
        try {
            this.connection = DriverManager.getConnection(HOST,USERNAME,PASSWORD);
        } catch (SQLException e) {
            System.err.println("Ошибка в подключении к БД");
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        return connection;
    }
}


There is also a class that listens for socket events on a port in a new thread (the run() method):
ObjectInputStream inputStream   = new ObjectInputStream(this.socket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(this.socket.getOutputStream());
            Ping ping = (Ping) inputStream.readObject();    /// --- это объект которые хранит передаваемые данные
            /// event handler
            while (true){
                if(!ping.isClear()){

                    switch (ping.getEventId()){
                        /* event Register */
                        case 1: {
                            Ping out = User.registrationUser(ping.getLogin(),ping.getPassword());  //// - здесь регистрируется пользователь, и данные сохраняются в БД.
                            outputStream.writeObject(out);
                            break;
                        }
                        case 2: {
                            System.out.println("event 2");
                            break;
                        }
                    }
                }
            }

Here is the method code:
public static Ping registrationUser(String login, String password) throws SQLException {
        Ping ping = new Ping("No error");
        Connection connect = new MySQLConntection().getConnection();
        Statement st = connect.createStatement();
        ResultSet rs = st.executeQuery("SELECT login FROM users");
        while (rs.next()){
            if(rs.getString(1) == login){
                ping.setError("Данный логин уже существует");
            }
        }
        if (ping.getError() == "No error"){
            PreparedStatement pr = connect.prepareStatement("INSERT INTO users (login, password) VALUES (?, md5(?))");
            pr.setString(1,login);
            pr.setString(2,password);
            pr.execute();
        }
        return ping;
    }

Well, the essence of the question is - when do you need to close the connection to the database and where is it better to push it? And if there are tips on the quality of the code, I will take note and refactor)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yerlan Ibraev, 2018-01-18
@TheRevan

RTFM?!

try {
  Connection connect = new MySQLConntection().getConnection();
...
}
finally {
  connection.close();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question