I didn’t quite understand your question, but I think I can help you by showing you how I made my connection to my database via JDBC Java.
package com.mypet.MyPet.persistence;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConectionMySql {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/MyPet?autoReconnect=true&useSSL=false";
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String LOGIN = "root";
private static final String PASSWORD = "toor";
public static Connection connection;
private ConectionMySql(){}
public static void openConection(){
try{
Class.forName(DRIVER);
ConectionMySql.connection = (Connection) DriverManager.getConnection(URL, LOGIN, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void closeConection(){
try {
if(!ConectionMySql.connection.isClosed()){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This is my class that I make the connection with Mysql Bank, I have a way to open and close the connection with the bank, giving a try catch
.
Whenever I go to make some call in the bank via Java, I open the connection with the method openConection
and close with the closeConection
, so in case of any error in connection the application will be aware as it always opens and closes before each call.
public T insert(T object) {
ConectionMySql.openConection();
try {
PreparedStatement preparedStatement = (PreparedStatement) ConectionMySql.connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
this.setStatementValuesToInsert(preparedStatement, object);
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()){
object = this.prepareObjectToResponse(resultSet.getLong(1), object);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
ConectionMySql.closeConection();
}
return object;
}
Where you can see the ConectionMySql.openConection();
and in Finally the ConectionMySql.closeConection();
.
I hope to have helped in some way, if you want, can access the code above in my Github in the school project Mypet, Made Back in Java with Spring and JDBC.
It’s just that in my case I used a Singleton, which means I only charge the connection class once. It happens that when I do getConnection returns the instance but it may be that the bank has fallen.
– Dener Alencar