Is the MySQL procedure in this Minecraft plugin correct? - java

To get an idea of what the basic structure looks like, I downloaded a money system including MySQL from Spigot and looked at the code.
public static boolean playerExists(String uuid) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
return (rs.getString("UUID") != null);
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static void createPlayer(String uuid) {
if (!playerExists(uuid))
Simplecoinsystem.mysql.update("INSERT INTO CoinData (UUID, COINS) VALUES ('" + uuid +
"', '" + Simplecoinsystem.getInstance().getConfig().getInt("startcoins") + "');");
}
public static Integer getCoins(String uuid) {
Integer i = Integer.valueOf(0);
if (playerExists(uuid)) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
Integer.valueOf(rs.getInt("COINS"));
i = Integer.valueOf(rs.getInt("COINS"));
} catch (SQLException e) {
e.printStackTrace();
}
} else {
createPlayer(uuid);
}
return i;
}
public static void setCoins(String uuid, Integer coins) {
if (playerExists(uuid)) {
Simplecoinsystem.mysql.update("UPDATE CoinData SET COINS= '" + coins + "' WHERE UUID= '" + uuid + "';");
} else {
createPlayer(uuid);
}
}
Am I correct that it is actually impractical to create a new entry with the uuid of the non-existent player after each query of the coins if the player does not exist?
Wouldn't this make it possible to flood the database with thousands of unnecessary entries by issuing, for example, a "/money (player)" command as an evil player/admin?
Couldn't I just ask when entering the server if the uuid is already stored and if not, just enter it? This way there would only be entries from players who have already been on the server before. Whether this needs great server performance, I'm not sure.
This is my first own MySQL class.
public class MySQL {
private String host, database, user, password;
private int port;
private Connection con;
public MySQL(String host, int port, String database, String user, String password) {
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
connect();
}
public void connect() {
try {
con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
System.out.println("&cDie MySQL Verbindung wurde erfolgreich aufgebaut!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
if(this.con != null) {
this.con.close();
System.out.println("§cDie MySQL Verbindung wurde erfolgreich beendet!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(String query) {
try {
Statement st = con.createStatement();
st.executeUpdate(query);
st.close();
} catch (Exception e) {
e.printStackTrace();
connect();
}
}
public ResultSet qry(String query) {
ResultSet rs = null;
try {
Statement st = con.createStatement();
rs = st.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
connect();
}
return rs;
}
public Connection getConnection() {
return this.con;
}
}
Except for this part, both MySQL classes are built relatively the same.
This is the part that is in the MySQL class of the Spigot plugin.

Your code have multiple issues.
When the connection will be closed, next time you will have an error. In your Mysql class, I suggest you to do:
public Connection getConnection() {
if(con == null || con.isClosed())
connect();
return con;
}
Then, use it in all method like getConnection().prepareStatement().
You can be attacked with SQL Injection. To fix this, try to do something like:
PreparedStatement st = con.prepareStatement("SELECT * FROM CoinData WHERE UUID = ?");
st.setString(1, uuid.toString()); // Yes it start at 1 !!
st.executeUpdate();
With this, even with all values, you can't be attacked with injections.
You will have an error while getting coins:
if (rs.next()) // go to good line
Integer.valueOf(rs.getInt("COINS")); // useless convertion
i = Integer.valueOf(rs.getInt("COINS")); // error if no line.
You can just do:
if(rs.next())
i = rs.getInt("COINS");
If the column "UUID" is unique, you will not have duplicated lines.
Finally, about performance, it's better to do it one time: at login, instead of all time. You can also create an object stored in an hashmap to easier access to it, without using SQL, like that:
public static HashMap<UUID, Integer> coinsByPlayer = new HashMap<>();
OR:
public static HashMap<UUID, MyObject> coinsByPlayer = new HashMap<>();
public class MyObject {
private int coins = 0;
public MyObject(UUID uuid) {
// make SQL request to get data
}
public int getCoins() {
return coins;
}
public void setCoins(int next){
coins = next;
// here make "UPDATE" sql query
}
}

What do you say? Is it ok with the try/catch function? #Elikill58
public Connection getConnection() {
try {
if(con == null || con.isClosed()) {
connect();
}
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
edit:
public Connection getConnection_one() throws SQLException {
if(con == null || con.isClosed()) {
connect();
return con;
} else {
return con;
}
}

Related

What is the right way to deal with the PreparedStatement in the Java program flow?

There are two methods in which the PreparedStatement is used.
The first method is called in the second method.
First method:
protected List<String> findResultsByMandantId(Long mandantId) {
List<String> resultIds = new ArrayList<>();
ResultSet rs;
String sql = "SELECT result_id FROM results WHERE mandant_id = ?";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.setLong(1, mandantId);
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
resultIds.add(rs.getString(1));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return resultIds;
}
Second method:
protected void findResultLineEntityToDelete(Long mandantId, String title, String context) {
List<String> resultIds = findResultsByMandantId(mandantId);
String [] resultIdsArr = resultIds.toArray(String[]::new);
ResultSet rs;
//String sql = "SELECT * FROM resultline WHERE result_id in (SELECT result_id FROM results WHERE mandant_id =" + mandantId + ")";
String sql = "SELECT * FROM resultline WHERE result_id in (" + String.join(", ", resultIdsArr)+ ")";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
if (rs.getString(3).equals(title) && rs.getString(4).equals(context)) {
System.out.println("Titel: " + rs.getString(3) + " " + "Context: " + rs.getString(4));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The class in which both methods are located extends the JDBCBaseManager.
JDBCBaseManager:
private final String url = "jdbc:mysql://localhost:3306/database";
private final String userName = "root";
private final String password = "";
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private int batchSize = 0;
public JDBCBaseManager() {
// Dotenv env = Dotenv.configure().directory("./serverless").load();
// url = env.get("DB_PROD_URL");
// userName = env.get("DB_USER");
// password = env.get("DB_PW");
}
public void getConnection() {
try {
if (connection == null) {
connection = DriverManager.getConnection(url, userName, password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
if (connection == null) {
getConnection();
}
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void startBatch(int batchSize) throws SQLException {
connection.setAutoCommit(false);
setBatchSize(batchSize);
}
public void commit() {
try {
if (connection != null && !connection.isClosed()) {
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
The ResultSet in the second method still contains the results from the first method.
I already tried to close the connection and open it again before the second method is executed, but then I get the errors:
java.sql.SQLException: No operations allowed after statement closed.
java.sql.SQLNonTransientConnectionException: No operations allowed
after connection closed.
Can you tell me how to deal with the statement correctly in this case? Is my BaseManager incorrectly structured?
Here lies the error
public JDBCBaseManager() {
private PreparedStatement preparedStatement = null;
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
......
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
You build the prepare statement only the first time the method getPreparedStatement is called because only the first time the field preparedStatement is null. Every next time you call the method getPreparedStatement you receive the previous preparedStatement from the previous SQL and not the new one.
Remove the check for if (preparedStatement == null) {
You need to build a new preparedStatement every time you want to execute a new SQL.

Discord bot unusually repeats

So I'm trying to create a discord bot that has simple access to a database for printing out values, my code currently will print the values to the discord server but it repeats them 5 times.
Bot functionality class:
private MySQLAccess sql = new MySQLAccess();
public static void main(String[] args) throws Exception {
JDABuilder ark = new JDABuilder(AccountType.BOT);
ark.setToken("insert_discord_token_here");
ark.addEventListener(new MessageListener());
ark.buildAsync();
}
#Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) return;
Message msg = e.getMessage();
String str = msg.getContentRaw();
//Ping pong
if (str.equalsIgnoreCase("!ping")) {
e.getChannel().sendMessage("Pong!").queue();
}
//Bal check
if (str.contains("!bal")) {
String user = str.substring(5);
System.out.println(user);
try {
sql.readDataBase(e.getChannel(), user);
} catch (Exception e1) {
}
}
}
Database Access Class:
private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
private final String user = "pass";
private final String pass = "user";
public void readDataBase(MessageChannel msg, String username) throws Exception {
//Retrieve data and search for username
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/serverusers?allowPublicKeyRetrieval=true&useSSL=false", user, pass);
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from serverusers.userinfo where user=\"" + username + "\"");
writeResultSet(resultSet, msg);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet, MessageChannel msg) throws SQLException {
// Check resultSet and print its contents
if (resultSet.next()) {
String user = resultSet.getString(2);
Double website = resultSet.getDouble(3);
msg.sendMessage("User: " + user).queue();
msg.sendMessage("Bank Amount: " + website).queue();
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
When the program is run it finds the correct data that I'm looking for and the search function is fine, but for some odd reason the program will spit the same username and balance out 5 times.
Screenshot of Discord Bot
The common mistake here is that you run the program multiple times, each instance then responds accordingly with the same thing. You can check if that is the case by opening the task manager and looking for java processes. This often occurs with developers using the Eclipse IDE because of the console hiding other processes behind a drop-down menu on the console.

MYSQL JDBC java.sql.SQLException: Operation not allowed after ResultSet closed

I have a program that queries a database using different jdbc drivers. This error is specific to the MySQL driver.
Here's the basic rundown.
I have another query runner class that uses a postgresql jdbc driver that works just fine. Note the line conn.close(); this works fine on my postgresql query runner, but for this SQL runner it comes up with the error.
I have removed the line conn.close(); and this code works fine, but over time it accumulates sleeping connections in the database. How can I fix this?
New Relic is a third party application that I am feeding data to, if you dont know what it is, don't worry it's not very relevant to this error.
MAIN CLASS
public class JavaPlugin {
public static void main(String[] args) {
try {
Runner runner = new Runner();
runner.add(new MonitorAgentFactory());
runner.setupAndRun(); // never returns
}
catch (ConfigurationException e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
}
}
MYSQL QUERY RUNNER CLASS
import com.newrelic.metrics.publish.util.Logger;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryRunner {
private static final Logger logger = Logger.getLogger(MySQLQueryRunner.class);
private String connectionStr;
private String username;
private String password;
public MySQLQueryRunner(String host, long port, String database, String username, String password) {
this.connectionStr = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false";
this.username = username;
this.password = password;
}
private void logError(String message) {
logger.error(new Object[]{message});
}
private void logDebugger(String message) {
logger.debug(new Object[]{message});
}
private Connection establishConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logError("MySQL Driver could not be found");
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionStr, username, password);
logDebugger("Connection established: " + connectionStr + " using " + username);
} catch (SQLException e) {
logError("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public ResultSet run(String query) {
Connection conn = establishConnection();
if (conn == null) {
logError("Connection could not be established");
return null;
}
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
conn.close();
return rs;
} catch (SQLException e) {
logError("Failed to collect data from database");
e.printStackTrace();
return null;
}
}
}
AGENT CLASS
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import com.newrelic.metrics.publish.Agent;
public class LocalAgent extends Agent {
private MySQLQueryRunner queryRunner;
private String name;
private Map<String, Object> thresholds;
private int intervalDuration;
private int intervalCount;
public LocalAgent(String name, String host, long port, String database, String username, String password, Map<String, Object> thresholds, int intervalDuration) {
super("com.mbt.local", "1.0.0");
this.name = name;
this.queryRunner = new MySQLQueryRunner(host, port, database, username, password);
// this.eventPusher = new NewRelicEvent();
this.thresholds = thresholds;
this.intervalDuration = intervalDuration;
this.intervalCount = 0;
}
/**
* Description of query
*/
private void eventTestOne() {
String query = "select count(1) as jerky from information_schema.tables;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestOne");
event.add("jerky", rs.getInt("jerky"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* blah
*/
private void eventTestTwo() {
String query = "SELECT maxlen FROM information_schema.CHARACTER_SETS;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestTwo");
event.add("beef", rs.getString("maxlen"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void pollCycle() {
if (this.intervalCount % this.intervalDuration == 0) {
eventTestOne();
eventTestTwo();
this.intervalCount = 0;
}
// Always incrementing intervalCount, keeping track of poll cycles that have passed
this.intervalCount++;
}
#Override
public String getAgentName() {
return this.name;
}
}
The problem is that you are trying to access the ResultSet after the connection is closed.
You should open and close the connection in the method that is calling run() this way the connection will be open when you access and loop through the Resultset and close it in the finally block of the calling method.
Even better would be if you can just loop through the ResultSet in the run() method and add the data to an object and return the object, this way you can close it in the finally block of the run() method.

How to increase Testcoverage for Class that interacts with a Database?

I got a Java class called PatientRepositoryImpl, which contains some methods, that insert, delete or update Data in a MySql Database.
I've also written some Unit Tests for this class.
When i check the Coverage of my tests, i only get 59%, although almost every line of Code is marked green by the Coverage tool, except the SQL Exceptions.
I am new here and hope i did everything right, would be very thankful if someone could help me.
Here the code for my Repository and the Tests.
public class PatientRepositoryMySqlImpl implements PatientRepository {
private DatabaseConnection connection;
private PatientGenerator patientGenerator;
public PatientRepositoryMySqlImpl(DatabaseConnection connection, PatientGenerator patientGenerator) {
this.connection = connection;
this.patientGenerator = patientGenerator;
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#insertPatient()
*/
#Override
public void insertPatient(Patient patient) {
if (!patient.isValid()) {
throw new IllegalArgumentException("Incomplete Patient");
} else {
String insert = "INSERT INTO tbl_patient(lastname, firstname, gender, birthday) VALUES('"
+ patient.getLastname() + "', '" + patient.getFirstname() + "', '" + patient.getGender() + "', '"
+ patient.getBirthday().toString() + "');";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.prepareStatement(insert)) {
statement.executeUpdate(insert);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#insertListOfPatients()
*/
#Override
public void insertListOfPatients(List<Patient> allPatients) {
for (Patient patient : allPatients) {
insertPatient(patient);
}
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#getRandomPatient()
*/
#Override
public Patient getRandomPatient() {
Patient patient = new Patient.Builder().build();
String query = "SELECT * FROM tbl_patient ORDER BY RAND() LIMIT 1";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.createStatement();) {
ResultSet rs = statement.executeQuery(query);
rs.next();
setPatientBasicData(patient, rs);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return patient;
}
private void setPatientBasicData(Patient patient, ResultSet rs) {
try {
patient.setId(rs.getInt("id"));
patient.setLastname(rs.getString("lastname"));
patient.setFirstname(rs.getString("firstname"));
patient.setGender(rs.getString("gender"));
patient.setBirthday(parseBirthday(rs.getString("birthday")));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public LocalDate parseBirthday(String birthday) {
LocalDate localDate = LocalDate.parse(birthday);
return localDate;
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#admitRandomPatient()
*/
#Override
public Patient admitRandomPatient() {
Patient patient = getRandomPatient();
patient.setDepartment(patientGenerator.getRandomDepartment());
patient.setWard(patientGenerator.getRandomWard());
patient.setAdmissionDateTime(LocalDateTime.now());
patient.setStatus("I");
String insert = "INSERT INTO tbl_inpatients(id, ward, department, admissionDate, patientStatus) VALUES('"
+ patient.getId() + "', '" + patient.getWard() + "', '" + patient.getDepartment() + "', '"
+ patient.getAdmissionDateTime().toString() + "', '" + patient.getStatus() + "')";
try (Connection dbConnection = connection.getDBConnection();
PreparedStatement statement = dbConnection.prepareStatement(insert)) {
statement.executeUpdate(insert, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = statement.getGeneratedKeys();
keys.next();
patient.setCaseId(keys.getInt(1));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return patient;
}
public Patient getRandomInpatient() {
Patient patient = new Patient.Builder().build();
String query = "SELECT * FROM tbl_inpatients ip, tbl_patient p WHERE p.id = ip.id ORDER BY RAND() LIMIT 1";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.createStatement();) {
ResultSet rs = statement.executeQuery(query);
rs.next();
setPatientBasicData(patient, rs);
setPatientCaseData(patient, rs);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return patient;
}
public void setPatientCaseData(Patient patient, ResultSet rs) {
try {
patient.setWard(rs.getString("ward"));
patient.setDepartment(rs.getString("department"));
patient.setAdmissionDateTime(parseLocalDateTime(rs.getString("admissionDate")));
patient.setStatus(rs.getString("patientStatus"));
patient.setCaseId(rs.getInt("case"));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public LocalDateTime parseLocalDateTime(String localdatetime) {
localdatetime = localdatetime.replace("T", "");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss.SSS");
LocalDateTime formattedLocalDateTime = LocalDateTime.parse(localdatetime, formatter);
return formattedLocalDateTime;
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#transferRandomPatient()
*/
#Override
public Patient transferRandomPatient() {
Patient patient = getRandomInpatient();
patient.setPriorWard(patient.getWard());
patient.setPriorDepartment(patient.getPriorDepartment());
patient.setDepartment(patientGenerator.getRandomDepartment());
patient.setWard(patientGenerator.getRandomWard());
String update = "UPDATE tbl_inpatients SET ward='" + patient.getWard() + "', department='"
+ patient.getDepartment() + "' WHERE id='" + patient.getId() + "'";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.prepareStatement(update)) {
statement.executeUpdate(update);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return patient;
}
/* (non-Javadoc)
* #see com.id.hl7sim.PatientRepository#dischargeRandomPatient()
*/
#Override
public Patient dischargeRandomPatient() {
Patient patient = getRandomInpatient();
patient.setDischargeDateTime(LocalDateTime.now());
insertFormerPatient(patient);
String delete = "DELETE FROM tbl_inpatients WHERE `case`=" + patient.getCaseId();
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.prepareStatement(delete)) {
statement.executeUpdate(delete);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return patient;
}
public void insertFormerPatient(Patient patient) {
String insert = "INSERT INTO tbl_formerpatients(`case`, `id`, ward, department, admissionDate, dischargeDate) VALUES('"
+ patient.getCaseId() + "', '" + patient.getId() + "', '" + patient.getWard() + "', '"
+ patient.getDepartment() + "', '" + patient.getAdmissionDateTime().toString() + "', '"
+ patient.getDischargeDateTime().toString() + "')";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.prepareStatement(insert)) {
statement.executeUpdate(insert);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public int countInpatients() {
int numberOfPatients = 0;
String query = "SELECT COUNT(id) AS numberOfPatients FROM tbl_inpatients";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.createStatement();) {
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
numberOfPatients = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return numberOfPatients;
}
public int countPatients() {
int numberOfPatients = 0;
String query = "SELECT COUNT(id) AS numberOfPatients FROM tbl_patient";
try (Connection dbConnection = connection.getDBConnection();
Statement statement = dbConnection.createStatement();) {
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
numberOfPatients = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return numberOfPatients;
}
Tests
public class PatientRepositoryMySqlImplTest {
PatientRepository testPatientRepository;
Patient testPatient;
Patient testPatientTwo;
List<Patient> testBothPatients;
DatabaseConnection testConnection;
PatientGenerator testPatientGenerator;
Firstnames testFirstnames;
Lastnames testLastnames;
Departments testDepartments;
Wards testWards;
#Before
public void setUp() throws Exception {
testDepartments = JAXB.unmarshal(ClassLoader.getSystemResource("departments.xml"), Departments.class);
testWards = JAXB.unmarshal(ClassLoader.getSystemResource("wards.xml"), Wards.class);
testLastnames = JAXB.unmarshal(ClassLoader.getSystemResource("lastnames.xml"), Lastnames.class);
testFirstnames = JAXB.unmarshal(ClassLoader.getSystemResource("firstnames.xml"), Firstnames.class);
testPatientGenerator = new PatientGeneratorImpl(testFirstnames, testLastnames, testDepartments, testWards);
testPatient = testPatientGenerator.randomizeNewPatient();
testPatientTwo = testPatientGenerator.randomizeNewPatient();
testBothPatients = new ArrayList<Patient>();
testConnection = new MySqlConnection();
testPatientRepository = new PatientRepositoryMySqlImpl(testConnection, testPatientGenerator);
testPatientRepository.admitRandomPatient();
}
#Test
public void testAdmitRandomPatient() {
testPatient = testPatientRepository.admitRandomPatient();
assertTrue(testPatient.isValid());
}
#Test
public void testGetRandomInpatient() {
testPatient = testPatientRepository.getRandomInpatient();
assertTrue(testPatient.isValid());
}
#Test
public void testDischargeRandomPatientValid() {
testPatient = testPatientRepository.dischargeRandomPatient();
assertTrue(testPatient.isValid());
assertTrue(testPatient.getCaseId() != 0);
}
#Test
public void testDischargeRandomPatientDatabase() {
int beforeDischarge = testPatientRepository.countInpatients();
testPatient = testPatientRepository.dischargeRandomPatient();
int afterDischarge = testPatientRepository.countInpatients();
assertTrue(afterDischarge == beforeDischarge - 1);
}
#Test(expected = IllegalArgumentException.class)
public void testInsertPatientWitIncompletePatient() {
testPatient.setFirstname("");
testPatientRepository.insertPatient(testPatient);
}
#Test
public void testTransferRandomPatient() {
testPatient = testPatientRepository.transferRandomPatient();
assertTrue(testPatient.getDepartment() != testPatient.getPriorDepartment());
}
#Test
public void testInsertPatient() {
int numberOfPatients = testPatientRepository.countInpatients();
testPatientRepository.insertPatient(testPatient);
assertTrue(testPatientRepository.countInpatients() >= numberOfPatients);
}
#Test
public void testInsertListOfPatients() {
testBothPatients.add(testPatient);
testBothPatients.add(testPatientTwo);
int countInpatientsBeforeInsertion = testPatientRepository.countPatients();
testPatientRepository.insertListOfPatients(testBothPatients);
int countInpatientsAfterInsertion = testPatientRepository.countPatients();
assertTrue(countInpatientsAfterInsertion > countInpatientsBeforeInsertion);
}
Edit:
#Test
public void mockThrowsException() {
PatientRepository testPatientRepository = mock(PatientRepositoryMySqlImpl.class);
when(testPatientRepository.getRandomPatient()).thenThrow(SQLException.class);
testPatientRepository.admitRandomPatient();
}
While I completely agree that in order to increase the coverage you should definitely "simulate" the scenario that something goes wrong and SQLExceptions are thrown, let me introduce another approach that will also answer the question but hopefully give you another perspective.
JDBC is pretty cumbersome, and the tests that will throw SQL exceptions will probably not be the most pleasant tests to write. In addition, I see that you don't really deal with exceptions, and just log them in a console.
So maybe instead of trying to struggle with this, maybe you should consider to not work directly with JDBC but use some library that will wrap the hassle of JDBC usage for you. For example of such a library, take a look onto Spring JDBC Template, I know it's a pretty old stuff, but hey, working directly with JDBC is also probably not the most modern approach, so I'm trying to make fewer changes but still gain a value. Moreover one may say that its old and not fancy, I would say, a battle-tested library, that can be even without Spring itself.
Now since it wraps the JDBC Exception handling, among other things, the point is that you won't have to cover these cases at all. So your coverage will increase naturally.
Of course other low level and no-so-low level alternatives exist (like JDBI, or JOOQ to name a few), but this a different story, all of them will increase the coverage in a sense of a question you've asked.

Opening and closing database

I'm working on an application that records do my MySql database on my server. Every time I want to use the database, get the existing connection, if not, I think for the first time. When I do an insert or select, works very well, but followed that consultation, when it ends, I can never regain the connection and do not return to consultations.
My class of Database
public class Database {
/**
* Gets just one instance of the class
* Connects on construct
* #returns connection
*/
private Connection _conn = null;
private long timer;
//singleton code
private static Database DatabaseObject;
private Database() {}
public static Database connect() {
if (DatabaseObject == null)
DatabaseObject = new Database();
return DatabaseObject._connect();
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//end singleton code
/**
* Connects with the defined parameters on Config
* Prevents re-connection if object was already connected
* #throws SQLException
*/
private Database _connect() {
try {
if (this._conn == null || !this._conn.isValid(0)) {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties connProps = new Properties();
connProps.put("user", Config.Config.DB_USER);
connProps.put("password", Config.Config.DB_PASS);
this._conn = DriverManager.
getConnection("jdbc:" + Config.Config.DB_DBMS + "://" + Config.Config.DB_HOST + ":"
+ Config.Config.DB_PORT + "/" + Config.Config.DB_NAME, Config.Config.DB_USER, Config.Config.DB_PASS);
timer = System.currentTimeMillis();
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Could not connect to DB");
e.printStackTrace();
}
} else {
try {
long tmp = System.currentTimeMillis() - timer;
if (tmp > 1200000) { //3600000 one hour ; 1200000 twenty minutes
System.out.println("Forcing reconnection ("+tmp+" milliseconds passed since last connection)");
this.close();
this._connect();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Forcing reconnection");
this._conn = null;
this._connect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
/**
* Closes connections
* This has to be invoked when database connection is no longer needed
* #throws SQLException
*/
public void close() throws SQLException {
if (this._conn != null) {
this._conn.close();
this._conn = null;
}
}
/**
* Getter for connection
* #return
*/
public Connection get() {
return this._conn;
}
}
The following function I make a query:
private Statement sment = null;
private PreparedStatement psment = null;
private ResultSet rset = null;
public boolean existsByNameAndUserId(String md5, int userId, int eventId) {
Connection conn = Database.connect().get();
try {
psment = conn.prepareStatement("SELECT * FROM files "
+ "WHERE user_id = ? AND md5 = ? AND evento_id = ?");
psment.setInt(1, userId);
psment.setString(2, md5);
psment.setInt(3, eventId);
rset = psment.executeQuery();
if (rset.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void close() {
try { if (rset != null) rset.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (psment != null) psment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (sment != null) sment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
}
And in the next, I call the above function to find out whether or not a record with these characteristics, if not, I do an insert.
String SQL_INSERT = "INSERT INTO files (evento_id, user_id, path, thumb, preview, width, height, md5, numero_corredor, created, modified) "
+ "VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
public void save(List<components.File.Schema> files) throws SQLException {
try (
Connection conn = Database.connect().get();
PreparedStatement statement = conn.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (components.File.Schema file : files) {
if(!existsByNameAndUserId(file.getMd5(), file.getUserId(), file.getEventId())){
statement.setInt(1, file.getEventId());
statement.setInt(2, file.getUserId());
statement.setString(3, file.getPath());
statement.setString(4, file.getPreview());
statement.setString(5, file.getThumb());
statement.setInt(6, file.getWidth());
statement.setInt(7, file.getHeight());
statement.setString(8, file.getMd5());
statement.setString(9, null);
statement.addBatch();
i++;
if (i % 1000 == 0 || i == files.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
}
Your issue is due to the fact that you put Connection conn = Database.connect().get() in a try-with-resources statement which is what you are supposed to do but it closes your connection and when you call it again as the method _connect() doesn't have a valid test, it doesn't create a new connection. The valid test is this._conn == null || !this._conn.isValid(0), indeed in your original test you call this._conn.isValid(0) which will returns false in our context since the connection is closed so it won't create a new connection which is not what we want here.
Response Update: The second part of the problem is the fact that in the save method you call existsByNameAndUserId which closes the current connection, you should only close the statement and let the method save close the connection.

Categories