Answer the question
In order to leave comments, you need to log in
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;
}
}
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;
}
}
}
}
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;
}
Answer the question
In order to leave comments, you need to log in
RTFM?!
try {
Connection connect = new MySQLConntection().getConnection();
...
}
finally {
connection.close();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question