I have a live java server. It has a DatabaseManager class for database connection, operation and closing. But there are a lot of database activities going on (even more than 50 clients simultaneously connected and voting). The executeQuery method returns a ResultSet, so not every opened connections are closed because closing will empty ResultSet before returning. Is there a better way to address this?
public class DatabaseManager {
private Connection conn;
public static Logger logger;
public static String user = "root";
public static String pass = "";
public DatabaseManager() {
logger = LoggerFactory.getLogger("Utilities.DatabaseManager");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
}
}
public void startConnection() {
try {
conn = DriverManager.getConnection("jdbc:mysql:///youspinvotes",
user, pass);
logger.debug("Database connected");
} catch (SQLException e) {
logger.error("Unable to connect to Database");
logger.error(e.getMessage());
}
}
public ResultSet exececuteQuery(final String query) {
logger.debug("Executing query:" + query);
ResultSet resultSet = null;
try {
final Statement stmt = conn.createStatement();
resultSet = stmt.executeQuery(query);
logger.debug("Query executed");
} catch (Exception e) {
logger.error("Unable to execute query."+e.getLocalizedMessage());
resultSet = null;
}
return resultSet;
}
public int executeUpdate(final String query) {
logger.debug("Executing update query:" + query);
int rowsAffected = -1;
try {
final Statement stmt = conn.createStatement();
rowsAffected = stmt.executeUpdate(query);
stmt.close();
logger.debug("Update performed with "+rowsAffected+" rows changed.");
} catch (Exception e) {
logger.error(query + ": Unable to execute query. \n"+ e.getMessage());
}
return rowsAffected;
}
public void endConnection() {
logger.debug("Closing database connection");
try {
conn.close();
} catch (Exception e) {
logger.error("There was a problem closing the database connection.");
}
}
}
Since there are lot of creating and closing connections, resource and time is consumed. Is there any way I can enhance the performance? Is connection pooling good choice for this server? What is the most efficient way to implement this kind of servers?