Junior
Kaip teisingai uždaryti ryšį su duomenų baze?
sobes.tech AI
Atsakymas iš AI
Naudojant try-with-resources bloką:
// Išteklių deklaravimas, kurie bus automatiškai uždaryti
try (
Connection connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", ""); // Gauti Connection objektą
Statement statement = connection.createStatement(); // Sukurti Statement objektą
ResultSet resultSet = statement.executeQuery("SELECT 1") // Vykdyti užklausą ir gauti ResultSet
) {
// Darbas su duomenimis iš ResultSet arba kitų operacijų su baze atlikimas
while (resultSet.next()) {
System.out.println(resultSet.getInt(1));
}
} catch (SQLException e) {
// Galimų SQLException apdorojimas
e.printStackTrace();
}
Šio metodo privalumai:
- Automatinis uždarymas: Ištekliai (Connection, Statement, ResultSet) garantuotai bus uždaryti po
trybloko pabaigos, net jei įvyks išimtis. - Tvarkingas kodas: Nereikia aiškiai kviesti
close()finallybloke, kas sumažina boilerplate kodo kiekį. - Išimčių apdorojimas: Jei uždarant išteklius įvyks išimtis, ji nebus slopinama išimtimi, kilusia
trybloke.
Alternatyvus, mažiau pageidaujamas būdas — aiškus uždarymas finally bloke:
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT 1");
// Darbas su duomenimis
while (resultSet.next()) {
System.out.println(resultSet.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Aiškus išteklių uždarymas atvirkštine tvarka
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Šis būdas yra daugiau užimantis ir labiau linkęs į klaidas, ypač kai apdorojamos išimtys uždarant išteklius. Rekomenduojama naudoti try-with-resources.